#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "speechmanager.h"
#include "emotioncontroller.h"
#include "sensormanager.h"
#include "weathermanager.h"
#include "networkcontroller.h"
#include "devicemanager.h"
#include "cameramanager.h"
#include "config.h"
#include "chatdatabase.h"
#include "display_config.h"

#include <QApplication>
#include <QMessageBox>
#include <QDateTime>
#include <QDebug>
#include <QRandomGenerator>
#include <QPainter>
#include <QTimer>
#include <QThread>
#include <QMutex>
#include <QTextCursor>
#include <QTextDocument>
#include <QSlider>
#include <QPushButton>
#include <QComboBox>
#include <QButtonGroup>
#include <QStackedWidget>
#include <QAbstractItemView>
#include <QDir>
#include <QUrl>
#include <QFileInfo>
#include <cmath>

#define pushButton_start_listen pushButton_start_conversation
#define pushButton_stop_listen pushButton_stop_reply
#define label_speech_status label_conversation_status
#define textEdit_recognition textEdit_conversation
#define label_audio_wave label_conversation_status

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , m_speechManager(nullptr)
    , m_emotionController(nullptr)
    , m_sensorManager(nullptr)
    , m_weatherManager(nullptr)
    , m_networkController(nullptr)
    , m_deviceManager(nullptr)
    , m_cameraManager(nullptr)
    , m_ledController(nullptr)
    , m_navButtonGroup(nullptr)
    , m_statusUpdateTimer(new QTimer(this))
    , m_sensorUpdateTimer(new QTimer(this))
    , m_waveUpdateTimer(new QTimer(this))
    , m_idleTimer(new QTimer(this))
    , m_isListening(false)
    , m_isConnected(false)
    , m_autoRestartListening(false)  // 🆕 默认不自动重新开始监听
    , m_currentEmotion("neutral")
    , m_audioLevel(0.0)
    , m_wavePhase(0.0)
    , m_musicPlayer(nullptr)
    , m_isMusicPlaying(false)
    , m_currentMusicFile("sunday.mp3")
    , m_musicPausedForConversation(false)
    , m_musicVolume(70) // 默认音量70%
{
    ui->setupUi(this);
    
    // 🎨 应用现代化样式
    applyModernStyles();
    
    // 初始化管理器
    m_speechManager = new SpeechManager(this);
    m_emotionController = new EmotionController(this);
    m_sensorManager = new SensorManager(this);
    m_weatherManager = new WeatherManager(this);
    m_networkController = new NetworkController(this);
    m_deviceManager = new DeviceManager(this);
    m_cameraManager = new CameraManager(this);
    m_ledController = new LedController(this);
    
    setupNavigation();
    connectSignals();
    setupWaveDisplay();
    
    // 设置定时器
    m_statusUpdateTimer->setInterval(1000); // 每秒更新
    m_sensorUpdateTimer->setInterval(2000); // 每2秒更新传感器（已禁用）
    m_waveUpdateTimer->setInterval(50); // 20fps波浪更新
    
    connect(m_statusUpdateTimer, &QTimer::timeout, this, &MainWindow::updateStatusDisplay);
    // 注释掉传感器更新，因为已被天气数据替代
    // connect(m_sensorUpdateTimer, &QTimer::timeout, this, &MainWindow::onSensorDataUpdated);
    connect(m_waveUpdateTimer, &QTimer::timeout, this, &MainWindow::updateWaveDisplay);
    
    m_statusUpdateTimer->start();
    // 不启动传感器定时器，因为已被天气数据替代
    // m_sensorUpdateTimer->start();
    
    // 初始状态 - 1080×1850，但允许用户自由缩放/最大化/最小化
    setWindowTitle("RK3588智能交互系统");
    setMinimumSize(640, 360);   // 给一个合理的最小尺寸
    resize(1080, 1850);         // 初始大小
    
    logMessage("系统启动完成，正在初始化组件...");
    
    // 初始化设备
    if (m_deviceManager) {
        m_deviceManager->initializeDevices();
    }
    
    // 初始化摄像头
    if (m_cameraManager) {
        m_cameraManager->setDisplayLabel(ui->label_camera_display);
    }
    
    // 🎵 初始化音乐播放器
    m_musicPlayer = new QMediaPlayer(this);
    m_musicPlayer->setVolume(m_musicVolume); // 设置默认音量
    connect(m_musicPlayer, QOverload<QMediaPlayer::State>::of(&QMediaPlayer::stateChanged), 
            this, &MainWindow::onMusicStateChanged);
    connect(m_musicPlayer, &QMediaPlayer::positionChanged, this, &MainWindow::onMusicPositionChanged);
    connect(m_musicPlayer, &QMediaPlayer::durationChanged, this, &MainWindow::onMusicDurationChanged);
    
    // 初始化音乐播放列表
    initializeMusicPlaylist();
    
    // 设置初始状态
    updateStatusDisplay();
    updateEmotionDisplay();
    
    // 初始化城市下拉框 - 使用UI设计器中的组件
    if (m_weatherManager) {
        // 清空下拉框
        ui->comboBox_city->clear();
        
        // 添加城市选项
        ui->comboBox_city->addItem("北京");
        ui->comboBox_city->addItem("上海");
        ui->comboBox_city->addItem("广州");
        ui->comboBox_city->addItem("深圳");
        ui->comboBox_city->addItem("杭州");
        ui->comboBox_city->addItem("南京");
        ui->comboBox_city->addItem("武汉");
        ui->comboBox_city->addItem("成都");
        ui->comboBox_city->addItem("西安");
        ui->comboBox_city->addItem("重庆");
        ui->comboBox_city->addItem("天津");
        ui->comboBox_city->addItem("苏州");
        ui->comboBox_city->addItem("青岛");
        ui->comboBox_city->addItem("大连");
        ui->comboBox_city->addItem("厦门");
        
        // 设置默认选项
        ui->comboBox_city->setCurrentText("北京");
        
        // 初始化城市滑动栏
        ui->horizontalSlider_city->setMinimum(0);
        ui->horizontalSlider_city->setMaximum(14); // 15个城市，索引0-14
        ui->horizontalSlider_city->setValue(0);   // 默认北京
        ui->label_city_display->setText("当前: 北京");
        
        // 连接城市选择变化信号
        connect(ui->comboBox_city, QOverload<const QString &>::of(&QComboBox::currentTextChanged),
                this, [this](const QString &city) {
                    if (m_weatherManager && !city.isEmpty()) {
                        m_weatherManager->setCity(city);
                        // 同步滑动栏位置
                        int index = ui->comboBox_city->findText(city);
                        if (index >= 0) {
                            ui->horizontalSlider_city->setValue(index);
                            ui->label_city_display->setText("当前: " + city);
                        }
                    }
                });
        
        // 连接滑动栏变化信号
        connect(ui->horizontalSlider_city, &QSlider::valueChanged, this, &MainWindow::onCitySliderChanged);
        
        // 启动自动更新天气数据
        m_weatherManager->startAutoUpdate(30); // 30分钟更新一次
    }
    
    // 固定映射左右眼Hi3861设备IP
    m_networkController->addDevice(NetworkController::Display1, LEFT_EYE_IP, DISPLAY_DEVICE_PORT);
    m_networkController->addDevice(NetworkController::Display2, RIGHT_EYE_IP, DISPLAY_DEVICE_PORT);
    
    // 默认显示语音页面
    switchToPage(0);

    // 连接休眠定时器
    connect(m_idleTimer, &QTimer::timeout, this, &MainWindow::onIdleTimeout);
    resetIdleTimer();
    
    // 🔘 设置键盘焦点，确保能接收KEY7按键事件
    setFocusPolicy(Qt::StrongFocus);
    setFocus();
    
    logMessage("🔘 KEY7按键控制已启用，按下开发板KEY7可控制LED开关");
}

MainWindow::~MainWindow()
{
    if (m_statusUpdateTimer) {
        m_statusUpdateTimer->stop();
    }
    if (m_sensorUpdateTimer) {
        m_sensorUpdateTimer->stop();
    }
    if (m_waveUpdateTimer) {
        m_waveUpdateTimer->stop();
    }
    if (m_idleTimer) {
        m_idleTimer->stop();
    }
    
    logMessage("系统正在关闭...");
    delete ui;
}

void MainWindow::setupNavigation()
{
    // 创建导航按钮组
    m_navButtonGroup = new QButtonGroup(this);
    m_navButtonGroup->addButton(ui->pushButton_nav_speech, 0);
    m_navButtonGroup->addButton(ui->pushButton_nav_emotion, 1);
    m_navButtonGroup->addButton(ui->pushButton_nav_sensor, 2);
    m_navButtonGroup->addButton(ui->pushButton_nav_camera, 3);
    m_navButtonGroup->addButton(ui->pushButton_nav_system, 4);
    
    // 设置按钮为互斥模式
    m_navButtonGroup->setExclusive(true);
    
    // 连接按钮组信号
    connect(m_navButtonGroup, QOverload<int>::of(&QButtonGroup::idClicked),
            this, &MainWindow::switchToPage);
}

void MainWindow::switchToPage(int pageIndex)
{
    // 切换堆叠窗口页面
    ui->stackedWidget_content->setCurrentIndex(pageIndex);
    
    // 确保对应的导航按钮被选中
    if (m_navButtonGroup) {
        QAbstractButton *button = m_navButtonGroup->button(pageIndex);
        if (button && !button->isChecked()) {
            button->setChecked(true);
        }
    }
}

void MainWindow::setupWaveDisplay()
{
    // 设置语音波形显示区域 - 适配小屏幕 (临时使用语音标题标签)
    ui->label_speech_title->setStyleSheet(
        "QLabel {"
        "    background-color: #1e1e1e;"
        "    border: 1px solid #606060;"
        "    border-radius: 3px;"
        "    color: #27ae60;"
        "    font-size: 8px;"
        "}"
    );
    
    // 初始化波形数据
    m_waveData.resize(100);
    for (int i = 0; i < m_waveData.size(); ++i) {
        m_waveData[i] = 0.0;
    }
}

void MainWindow::connectSignals()
{
    // 导航信号
    connect(ui->pushButton_nav_speech, &QPushButton::clicked, this, &MainWindow::onNavSpeechClicked);
    connect(ui->pushButton_nav_emotion, &QPushButton::clicked, this, &MainWindow::onNavEmotionClicked);
    connect(ui->pushButton_nav_sensor, &QPushButton::clicked, this, &MainWindow::onNavSensorClicked);
    connect(ui->pushButton_nav_camera, &QPushButton::clicked, this, [this]() { switchToPage(3); });
    connect(ui->pushButton_nav_system, &QPushButton::clicked, this, &MainWindow::onNavSystemClicked);
    
    // 语音控制信号
    connect(ui->pushButton_start_conversation, &QPushButton::clicked, this, &MainWindow::onStartListening);
    connect(ui->pushButton_stop_reply, &QPushButton::clicked, this, &MainWindow::onStopListening);
    // 🎵 连接音乐控制按钮
    connect(ui->pushButton_stop_music, &QPushButton::clicked, this, &MainWindow::onStopMusic);
    // 仍保留热点按钮进行TTS测试
    connect(ui->pushButton_start_hotspot, &QPushButton::clicked, this, &MainWindow::onTestTTS);
    
    // 表情控制信号
    connect(ui->pushButton_happy, &QPushButton::clicked, this, &MainWindow::onSetHappyEmotion);
    connect(ui->pushButton_sad, &QPushButton::clicked, this, &MainWindow::onSetSadEmotion);
    connect(ui->pushButton_angry, &QPushButton::clicked, this, &MainWindow::onSetAngryEmotion);
    connect(ui->pushButton_surprised, &QPushButton::clicked, this, &MainWindow::onSetSurprisedEmotion);
    connect(ui->pushButton_fear, &QPushButton::clicked, this, &MainWindow::onSetFearEmotion);
    connect(ui->pushButton_neutral, &QPushButton::clicked, this, &MainWindow::onSetNeutralEmotion);
    
    // 设备连接测试信号
    connect(ui->pushButton_test_connection, &QPushButton::clicked, this, &MainWindow::onTestDeviceConnection);
    connect(ui->pushButton_reconnect_devices, &QPushButton::clicked, this, &MainWindow::onReconnectDevices);
    
    // 表情控制器连接状态信号
    if (m_emotionController) {
        connect(m_emotionController, &EmotionController::connectionStatusChanged,
                this, &MainWindow::onDeviceConnectionStatusChanged);
        connect(m_emotionController, &EmotionController::deviceTestResult,
                this, &MainWindow::onDeviceTestResult);
        connect(m_emotionController, &EmotionController::emotionChanged,
                this, &MainWindow::onEmotionChanged);
    }
    
    // 天气控制信号
    connect(ui->pushButton_refresh_weather, &QPushButton::clicked, this, &MainWindow::onRefreshSensorClicked);
    
    // 摄像头控制信号
    connect(ui->pushButton_camera_start, &QPushButton::clicked, this, &MainWindow::onCameraStart);
    connect(ui->pushButton_camera_stop, &QPushButton::clicked, this, &MainWindow::onCameraStop);
    connect(ui->pushButton_camera_snapshot, &QPushButton::clicked, this, &MainWindow::onCameraSnapshot);
    
    // 系统控制信号
    connect(ui->pushButton_reconnect, &QPushButton::clicked, this, &MainWindow::onReconnect);
    connect(ui->pushButton_settings, &QPushButton::clicked, this, &MainWindow::onSettingsClicked);
    connect(ui->comboBox_debug_level, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::onDebugLevelChanged);
    
    // 语音管理器信号
    if (m_speechManager) {
        connect(m_speechManager, &SpeechManager::speechRecognized, this, &MainWindow::onSpeechResult);
        connect(m_speechManager, &SpeechManager::speechError, this, &MainWindow::onSpeechError);
        connect(m_speechManager, &SpeechManager::ttsFinished, this, &MainWindow::onTTSFinished);
        connect(m_speechManager, &SpeechManager::wakeWordDetected, this, &MainWindow::onWakeWordDetected);
        connect(m_speechManager, &SpeechManager::audioLevelChanged, this, &MainWindow::onAudioLevelChanged);
    }
    
    // 天气管理器信号
    if (m_weatherManager) {
        connect(m_weatherManager, &WeatherManager::weatherDataUpdated, this, &MainWindow::onWeatherDataUpdated);
        connect(m_weatherManager, &WeatherManager::cityChanged, this, &MainWindow::onCityChanged);
        connect(m_weatherManager, &WeatherManager::errorOccurred, this, &MainWindow::onWeatherError);
    }
    
    // 设备管理器信号
    if (m_deviceManager) {
        connect(m_deviceManager, &DeviceManager::deviceConnectionChanged, this, &MainWindow::onDeviceConnectionChanged);
    }
    
    // 摄像头管理器信号
    if (m_cameraManager) {
        connect(m_cameraManager, &CameraManager::cameraStatusChanged, this, [this](bool active) {
            ui->label_camera_status->setText(QString("状态: %1").arg(active ? "在线" : "离线"));
            ui->label_camera_status->setStyleSheet(QString("QLabel { color: %1; font-size: 8px; font-weight: bold; }")
                                                   .arg(active ? "#27ae60" : "#e74c3c"));
        });
        
        connect(m_cameraManager, &CameraManager::frameRateChanged, this, [this](int fps) {
            ui->label_camera_fps->setText(QString("帧率: %1 FPS").arg(fps));
        });
        
        connect(m_cameraManager, &CameraManager::errorOccurred, this, &MainWindow::onCameraError);
        connect(m_cameraManager, &CameraManager::imageCaptured, this, [this](const QString &fileName) {
            logMessage(QString("照片已保存: %1").arg(fileName));
        });
    }
    
    // LED控制器信号
    if (m_ledController) {
        connect(m_ledController, &LedController::ledStateChanged, this, &MainWindow::onLedStateChanged);
        connect(m_ledController, &LedController::ledControlResult, this, &MainWindow::onLedControlResult);
        connect(m_ledController, &LedController::allLedsStateChanged, this, &MainWindow::onAllLedsStateChanged);
    }
    
    // 传感器管理器信号（已禁用，使用天气数据替代）
    // if (m_sensorManager) {
    //     connect(m_sensorManager, &SensorManager::temperatureChanged, this, &MainWindow::onTemperatureChanged);
    //     connect(m_sensorManager, &SensorManager::humidityChanged, this, &MainWindow::onHumidityChanged);
    //     connect(m_sensorManager, &SensorManager::lightChanged, this, &MainWindow::onLightChanged);
    // }
    
    // 天气管理器信号
    if (m_weatherManager) {
        connect(m_weatherManager, &WeatherManager::weatherDataUpdated, this, &MainWindow::onWeatherDataUpdated);
        connect(m_weatherManager, &WeatherManager::errorOccurred, this, &MainWindow::onWeatherError);
        
        // 初始化城市列表
        QStringList cities = m_weatherManager->getSupportedCities();
        ui->comboBox_city->clear();
        ui->comboBox_city->addItems(cities);
        
        QString currentCity = m_weatherManager->getCurrentCity();
        ui->comboBox_city->setCurrentText(currentCity);
        
        // 强制刷新显示
        ui->comboBox_city->update();
        ui->comboBox_city->repaint();
        
        // 连接城市选择信号（在添加项目后连接，避免初始化时触发）
        connect(ui->comboBox_city, QOverload<const QString &>::of(&QComboBox::currentTextChanged), 
                this, &MainWindow::onCityChanged);
        
        // 连接城市滑动栏信号
        connect(ui->horizontalSlider_city, &QSlider::valueChanged, this, &MainWindow::onCitySliderChanged);
        
        // 初始化滑动栏
        ui->horizontalSlider_city->setMaximum(cities.size() - 1);
        ui->horizontalSlider_city->setValue(ui->comboBox_city->currentIndex());
        ui->label_city_display->setText("当前: " + currentCity);
        
        // 启动自动更新
        m_weatherManager->startAutoUpdate(30); // 30分钟更新一次
        
        // 获取城市信息用于日志记录
        int cityCount = ui->comboBox_city->count();
        QString selectedCity = ui->comboBox_city->currentText();
        logMessage(QString("天气管理器初始化完成，支持%1个城市，当前城市: %2").arg(cityCount).arg(selectedCity));
        
        // 记录城市列表
        QStringList cityList;
        for (int i = 0; i < ui->comboBox_city->count(); ++i) {
            cityList << ui->comboBox_city->itemText(i);
        }
        logMessage(QString("城市列表: %1").arg(cityList.join(", ")));
    }
}

// 导航槽函数
void MainWindow::onNavSpeechClicked()
{
    switchToPage(0);
}

void MainWindow::onNavEmotionClicked()
{
    switchToPage(1);
}

void MainWindow::onNavSensorClicked()
{
    switchToPage(2);
}

void MainWindow::onNavSystemClicked()
{
    switchToPage(4);
}

// 语音控制槽函数
void MainWindow::onStartListening()
{
    if (m_speechManager) {
        m_isListening = true;
        m_autoRestartListening = true;  // 🆕 用户主动开始监听时，允许自动重新开始
        // 切换按钮可见性：隐藏"开始说话"，显示"结束说话"
        ui->pushButton_start_conversation->setVisible(false);
        ui->pushButton_stop_reply->setVisible(true);
        ui->pushButton_stop_reply->setEnabled(true);
        ui->label_conversation_status->setText("状态: 监听中");
        ui->label_conversation_status->setStyleSheet("QLabel { color: #f39c12; font-weight: bold; font-size: 8px; }");
        
        // 开始波形显示
        m_waveUpdateTimer->start();
        
        m_speechManager->startListening();
        logMessage("开始语音识别监听");
        updateStatusDisplay();
    }
}

void MainWindow::onStopListening()
{
    if (m_speechManager) {
        m_isListening = false;
        m_autoRestartListening = false;  // 🆕 用户主动停止监听时，禁止自动重新开始
        // 切换按钮可见性：显示"开始说话"，隐藏"结束说话"
        ui->pushButton_start_conversation->setVisible(true);
        ui->pushButton_start_conversation->setEnabled(true);
        ui->pushButton_stop_reply->setVisible(false);
        ui->pushButton_stop_reply->setEnabled(false);
        ui->label_conversation_status->setText("状态: 空闲");
        ui->label_conversation_status->setStyleSheet("QLabel { color: #27ae60; font-weight: bold; font-size: 8px; }");
        
        // 停止波形显示
        m_waveUpdateTimer->stop();
        m_audioLevel = 0.0;
        updateWaveDisplay();
        
        m_speechManager->stopListening();
        logMessage("停止语音识别监听");
        updateStatusDisplay();
    }
}

void MainWindow::onTestTTS()
{
    if (m_speechManager) {
        QString testText = "你好，这是RK3588智能表情交互系统的语音合成测试。";
        ui->label_conversation_status->setText("正在合成语音...");
        ui->label_conversation_status->setStyleSheet("QLabel { color: #2196F3; font-weight: bold; }");
        
        m_speechManager->synthesizeText(testText);
        logMessage("开始语音合成测试: " + testText);
    }
}

void MainWindow::onSpeechResult(const QString &text)
{
    ui->label_conversation_status->setText("处理中...");
    ui->label_conversation_status->setStyleSheet("QLabel { color: #FF9800; font-weight: bold; }");
    
    // 🔧 收到语音识别结果后立即停止监听，避免录制到自己的TTS声音
    if (m_speechManager && m_isListening) {
        m_speechManager->stopListening();
        logMessage("收到语音识别结果，停止监听");
    }
    
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString resultText = QString("[%1] %2").arg(timestamp, text);
    ui->textEdit_conversation->append(resultText);
    logMessage("语音识别结果: " + text);
    
    // 🆕 添加智能语音交互处理
    processVoiceCommand(text);
    
    // 自动滚动到底部
    QTextCursor cursor = ui->textEdit_conversation->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit_conversation->setTextCursor(cursor);
    ui->textEdit_conversation->ensureCursorVisible();

    // 重置休眠定时器
    resetIdleTimer();
}

void MainWindow::onSpeechError(const QString &error)
{
    ui->label_conversation_status->setText("语音错误: " + error);
    ui->label_conversation_status->setStyleSheet("QLabel { color: #f44336; font-weight: bold; }");
    logMessage("语音错误: " + error);
}

void MainWindow::onTTSFinished()
{
    ui->label_conversation_status->setText("回复完成");
    ui->label_conversation_status->setStyleSheet("QLabel { color: #4CAF50; font-weight: bold; }");
    logMessage("语音合成完成");
    
    // 🎵 TTS完成后，延迟恢复音乐播放（如果音乐是因对话而暂停的）
    QTimer::singleShot(1000, this, [this]() {
        resumeMusicAfterConversation();
    });
    
    // 🔧 只有在用户主动开始对话模式时，才自动重新开始监听
    if (m_autoRestartListening) {
        // 延迟重新开始监听，避免识别到自己的声音
        QTimer::singleShot(3000, [this]() { // 延迟3秒再启动，确保音频播放完全结束
            if (m_speechManager && m_autoRestartListening) { // 再次检查状态
                // 🆕 更新UI状态为监听状态
                m_isListening = true;
                ui->pushButton_start_conversation->setVisible(false);
                ui->pushButton_stop_reply->setVisible(true);
                ui->pushButton_stop_reply->setEnabled(true);
                m_waveUpdateTimer->start(); // 重新开始波形显示
                
                m_speechManager->startListening();
                ui->label_conversation_status->setText("请说话...");
                ui->label_conversation_status->setStyleSheet("QLabel { color: #2196F3; font-weight: bold; }");
                logMessage("准备下一轮对话，开始监听");
            }
        });
    } else {
        // 🆕 如果不是在对话模式，显示完成状态并提示用户手动开始
        ui->label_conversation_status->setText("回复完成，点击'开始说话'继续对话");
        ui->label_conversation_status->setStyleSheet("QLabel { color: #4CAF50; font-weight: bold; }");
        logMessage("TTS播放完成，等待用户手动开始下一轮对话");
    }
}

void MainWindow::onWakeWordDetected()
{
    logMessage("检测到唤醒词");
    onStartListening(); // 自动开始监听
}

void MainWindow::onAudioLevelChanged(double level)
{
    m_audioLevel = level;
    // updateWaveDisplay会在定时器中自动调用，使用最新的音频级别
}

// 表情控制槽函数
void MainWindow::onSetHappyEmotion()
{
    m_currentEmotion = "happy";
    updateEmotionDisplay();
    if (m_emotionController) {
        m_emotionController->setEmotion("happy", 100);
    }
    logMessage("设置表情: 开心");
}

void MainWindow::onSetSadEmotion()
{
    m_currentEmotion = "sad";
    updateEmotionDisplay();
    if (m_emotionController) {
        m_emotionController->setEmotion("sad", 100);
    }
    logMessage("设置表情: 伤心");
}

void MainWindow::onSetAngryEmotion()
{
    m_currentEmotion = "angry";
    updateEmotionDisplay();
    if (m_emotionController) {
        m_emotionController->setEmotion("angry", 100);
    }
    logMessage("设置表情: 愤怒");
}

void MainWindow::onSetSurprisedEmotion()
{
    m_currentEmotion = "surprised";
    updateEmotionDisplay();
    if (m_emotionController) {
        m_emotionController->setEmotion("surprised", 100);
    }
    logMessage("设置表情: 惊讶");
}

void MainWindow::onSetFearEmotion()
{
    m_currentEmotion = "fear";
    updateEmotionDisplay();
    if (m_emotionController) {
        m_emotionController->setEmotion("fear", 100);
    }
    logMessage("设置表情: 恐惧");
}

void MainWindow::onSetNeutralEmotion()
{
    m_currentEmotion = "neutral";
    updateEmotionDisplay();
    if (m_emotionController) {
        m_emotionController->setEmotion("neutral", 100);
    }
    logMessage("设置表情: 中性");
}

// 设备连接测试槽函数
void MainWindow::onTestDeviceConnection()
{
    logMessage("开始测试设备连接...");
    ui->label_device_status->setText("🔄 正在测试连接...");
    ui->label_device_status->setStyleSheet(
        "QLabel {"
        "    color: #3498db;"
        "    font-weight: bold;"
        "    font-size: 32px;"
        "    padding: 15px;"
        "    margin-top: 10px;"
        "    background-color: #ebf3fd;"
        "    border: 2px solid #3498db;"
        "    border-radius: 10px;"
        "}"
    );
    
    if (m_emotionController) {
        m_emotionController->testDeviceConnection();
    }
}

void MainWindow::onReconnectDevices()
{
    logMessage("正在重新连接眼睛设备...");
    ui->label_device_status->setText("🔄 重新连接中...");
    ui->label_device_status->setStyleSheet(
        "QLabel {"
        "    color: #e67e22;"
        "    font-weight: bold;"
        "    font-size: 32px;"
        "    padding: 15px;"
        "    margin-top: 10px;"
        "    background-color: #fef5e7;"
        "    border: 2px solid #e67e22;"
        "    border-radius: 10px;"
        "}"
    );
    
    if (m_emotionController) {
        // 触发设备重新发现
        m_emotionController->testDeviceConnection();
    }
}

void MainWindow::onDeviceConnectionStatusChanged(bool leftEye, bool rightEye)
{
    QString statusText;
    QString styleSheet;
    
    if (leftEye && rightEye) {
        statusText = "✅ 双眼连接正常";
        styleSheet = "QLabel {"
                    "    color: #27ae60;"
                    "    font-weight: bold;"
                    "    font-size: 32px;"
                    "    padding: 15px;"
                    "    margin-top: 10px;"
                    "    background-color: #eafaf1;"
                    "    border: 2px solid #27ae60;"
                    "    border-radius: 10px;"
                    "}";
    } else if (leftEye || rightEye) {
        statusText = QString("⚠️ %1连接正常").arg(leftEye ? "左眼" : "右眼");
        styleSheet = "QLabel {"
                    "    color: #f39c12;"
                    "    font-weight: bold;"
                    "    font-size: 32px;"
                    "    padding: 15px;"
                    "    margin-top: 10px;"
                    "    background-color: #fef9e7;"
                    "    border: 2px solid #f39c12;"
                    "    border-radius: 10px;"
                    "}";
    } else {
        statusText = "❌ 设备未连接";
        styleSheet = "QLabel {"
                    "    color: #e74c3c;"
                    "    font-weight: bold;"
                    "    font-size: 32px;"
                    "    padding: 15px;"
                    "    margin-top: 10px;"
                    "    background-color: #fadbd8;"
                    "    border: 2px solid #e74c3c;"
                    "    border-radius: 10px;"
                    "}";
    }
    
    ui->label_device_status->setText(statusText);
    ui->label_device_status->setStyleSheet(styleSheet);
    
    // 更新左眼显示框状态
    if (leftEye) {
        ui->label_left_eye_status->setText("✅ 已连接");
        ui->label_left_eye_status->setStyleSheet("QLabel { color: #27ae60; font-weight: bold; font-size: 24px; background-color: transparent; border: none; margin: 0px; padding: 5px; }");
        ui->frame_left_eye->setStyleSheet("QFrame { background-color: #d5f4e6; border: 3px solid #27ae60; border-radius: 15px; margin: 5px; }");
    } else {
        ui->label_left_eye_status->setText("❌ 未连接");
        ui->label_left_eye_status->setStyleSheet("QLabel { color: #e74c3c; font-weight: bold; font-size: 24px; background-color: transparent; border: none; margin: 0px; padding: 5px; }");
        ui->frame_left_eye->setStyleSheet("QFrame { background-color: #95a5a6; border: 3px solid #7f8c8d; border-radius: 15px; margin: 5px; }");
    }
    
    // 更新右眼显示框状态
    if (rightEye) {
        ui->label_right_eye_status->setText("✅ 已连接");
        ui->label_right_eye_status->setStyleSheet("QLabel { color: #27ae60; font-weight: bold; font-size: 24px; background-color: transparent; border: none; margin: 0px; padding: 5px; }");
        ui->frame_right_eye->setStyleSheet("QFrame { background-color: #d5f4e6; border: 3px solid #27ae60; border-radius: 15px; margin: 5px; }");
    } else {
        ui->label_right_eye_status->setText("❌ 未连接");
        ui->label_right_eye_status->setStyleSheet("QLabel { color: #e74c3c; font-weight: bold; font-size: 24px; background-color: transparent; border: none; margin: 0px; padding: 5px; }");
        ui->frame_right_eye->setStyleSheet("QFrame { background-color: #95a5a6; border: 3px solid #7f8c8d; border-radius: 15px; margin: 5px; }");
    }
    
    logMessage(QString("设备连接状态更新: 左眼=%1, 右眼=%2")
               .arg(leftEye ? "连接" : "断开")
               .arg(rightEye ? "连接" : "断开"));
}

void MainWindow::onDeviceTestResult(int deviceIndex, bool success)
{
    QString deviceName = (deviceIndex == 0) ? "左眼" : "右眼";
    logMessage(QString("%1设备测试结果: %2").arg(deviceName).arg(success ? "成功" : "失败"));
}

void MainWindow::onEmotionChanged(const QString &emotion, int intensity)
{
    ui->label_current_emotion->setText(QString("当前表情: %1 (强度: %2%)").arg(emotion).arg(intensity));
    logMessage(QString("表情已更新: %1, 强度: %2%").arg(emotion).arg(intensity));
}



// 传感器数据槽函数
void MainWindow::onSensorDataUpdated()
{
    if (m_sensorManager) {
        // 模拟传感器数据更新
        double temp = 25.0 + (QRandomGenerator::global()->bounded(100)) / 10.0; // 25-35°C
        double humidity = 50.0 + (QRandomGenerator::global()->bounded(300)) / 10.0; // 50-80%
        int light = QRandomGenerator::global()->bounded(500) + 50; // 50-550 lux
        
        onTemperatureChanged(temp);
        onHumidityChanged(humidity);
        onLightChanged(light);
    }
}

void MainWindow::onTemperatureChanged(double temperature)
{
    // 温度显示，根据温度范围设置颜色
    QString color = "#27ae60"; // 绿色 - 适宜
    if (temperature > 35.0) {
        color = "#e74c3c"; // 红色 - 高温
    } else if (temperature > 30.0) {
        color = "#f39c12"; // 橙色 - 偏热  
    } else if (temperature < 18.0) {
        color = "#3498db"; // 蓝色 - 低温
    }
    
    ui->label_temperature->setText(QString("%1°C").arg(temperature, 0, 'f', 1));
    ui->label_temperature->setStyleSheet(QString("QLabel { color: %1; font-weight: bold; }").arg(color));
}

void MainWindow::onHumidityChanged(double humidity)
{
    // 湿度显示，根据湿度范围设置颜色
    QString color = "#3498db"; // 蓝色 - 适宜
    if (humidity > 70.0) {
        color = "#f39c12"; // 橙色 - 潮湿  
    } else if (humidity < 40.0) {
        color = "#e74c3c"; // 红色 - 干燥
    }
    
    ui->label_humidity->setText(QString("%1%").arg(humidity, 0, 'f', 1));
    ui->label_humidity->setStyleSheet(QString("QLabel { color: %1; font-weight: bold; }").arg(color));
}

void MainWindow::onLightChanged(int light)
{
    // 光照传感器功能已被天气数据替代
    // 这个函数保留用于兼容性，但不再更新UI
    logMessage(QString("光照传感器数据: %1 lux (已被天气数据替代)").arg(light));
}

// 传感器按钮槽函数（保留用于兼容性）
void MainWindow::onCalibrateClicked()
{
    logMessage("校准功能已移除，现在使用天气数据");
}

void MainWindow::onRefreshSensorClicked()
{
    logMessage("刷新天气数据...");
    if (m_weatherManager) {
        m_weatherManager->refreshWeatherData();
    }
}

// 新增系统按钮槽函数
void MainWindow::onSettingsClicked()
{
    logMessage("打开系统设置...");
    // 这里可以打开设置对话框
    // QMessageBox::information(this, "设置", "设置功能正在开发中...");
}

// 系统控制槽函数
void MainWindow::onReconnect()
{
    logMessage("尝试重新连接设备...");
    ui->label_system_status->setText("系统运行中 | 连接: 连接中");
    ui->label_system_status->setStyleSheet("QLabel { color: #f39c12; font-weight: bold; font-size: 8px; }");
    
    if (m_deviceManager) {
        m_deviceManager->reconnectDevices();
    }
    
    // 模拟连接过程
    QTimer::singleShot(2000, [this]() {
        bool connected = QRandomGenerator::global()->bounded(2) == 1;
        onDeviceConnectionChanged(connected);
    });
}

void MainWindow::onDebugLevelChanged(int index)
{
    QStringList levels = {"信息", "警告", "错误", "调试"};
    if (index >= 0 && index < levels.size()) {
        logMessage("调试级别更改为: " + levels[index]);
    }
}

void MainWindow::onDeviceConnectionChanged(bool connected)
{
    m_isConnected = connected;
    if (connected) {
        ui->label_system_status->setText("系统运行中 | 连接: 是");
        ui->label_system_status->setStyleSheet("QLabel { color: #27ae60; font-weight: bold; font-size: 8px; }");
        logMessage("设备连接成功");
    } else {
        ui->label_system_status->setText("系统运行中 | 连接: 否");
        ui->label_system_status->setStyleSheet("QLabel { color: #e74c3c; font-weight: bold; font-size: 8px; }");
        logMessage("设备连接失败");
    }
    updateStatusDisplay();
}

// 菜单槽函数（保留用于快捷键支持）
void MainWindow::onShowSettings()
{
    onSettingsClicked();
}

void MainWindow::onCalibrateDevices()
{
    logMessage("设备校准功能已更新为天气数据刷新");
    if (m_weatherManager) {
        m_weatherManager->refreshWeatherData();
    }
}

void MainWindow::onTestDisplays()
{
    logMessage("测试显示屏...");
    // 可以在这里添加显示屏测试逻辑
}

void MainWindow::onShowAbout()
{
    QMessageBox::about(this, "关于", 
        "RK3588智能交互系统 v2.0\n\n"
        "基于Qt5开发的智能交互系统\n"
        "支持语音识别、表情控制、传感器监测等功能\n"
        "优化适配320x240分辨率显示屏\n\n"
        "开发团队: 系统能力大赛项目组");
}

// 显示更新函数
void MainWindow::updateStatusDisplay()
{
    QString status = QString("系统运行中 | 连接: %1")
                     .arg(m_isConnected ? "是" : "否");
    ui->label_system_status->setText(status);
}

void MainWindow::updateEmotionDisplay()
{
    QString emotionText = "中性";
    if (m_currentEmotion == "happy") {
        emotionText = "开心";
    } else if (m_currentEmotion == "sad") {
        emotionText = "伤心";
    } else if (m_currentEmotion == "angry") {
        emotionText = "愤怒";
    } else if (m_currentEmotion == "surprised") {
        emotionText = "惊讶";
    } else if (m_currentEmotion == "fear") {
        emotionText = "恐惧";
    }
    
    QString displayText = QString("当前表情: %1").arg(emotionText);
    ui->label_current_emotion->setText(displayText);
}

void MainWindow::updateWaveDisplay()
{
    if (!m_isListening) {
        ui->label_conversation_status->setText("音频波形");
        return;
    }
    
    // 更新波形相位
    m_wavePhase += 0.2;
    if (m_wavePhase > 2 * M_PI) {
        m_wavePhase -= 2 * M_PI;
    }
    
    // 生成简化的波形显示（适应小屏幕）
    QString waveText = "♪ ";
    double baseAmplitude = 0.3 + m_audioLevel * 0.7;
    
    for (int i = 0; i < 10; ++i) {
        double x = i * 0.8;
        double amplitude = baseAmplitude * sin(x + m_wavePhase);
        
        if (amplitude > 0.3) {
            waveText += "█";
        } else if (amplitude > 0.1) {
            waveText += "▆";
        } else if (amplitude > -0.1) {
            waveText += "▄";
        } else {
            waveText += "▂";
        }
    }
    waveText += " ♪";
    
    ui->label_conversation_status->setText(waveText);
    
    // 模拟音频级别变化
    if (m_isListening) {
        m_audioLevel = 0.1 + 0.4 * (sin(m_wavePhase * 2) + 1) / 2 + 
                      0.3 * QRandomGenerator::global()->bounded(100) / 100.0;
        m_audioLevel = qBound(0.0, m_audioLevel, 1.0);
    }
}

void MainWindow::logMessage(const QString &message)
{
    QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
    QString logEntry = QString("[%1] %2").arg(timestamp, message);
    
    // 在系统页面的日志文本框中显示
    ui->textEdit_logs->append(QString("<span style='color: #27ae60;'>%1</span>").arg(logEntry));
    
    // 限制日志行数，避免内存占用过多
    QTextDocument *doc = ui->textEdit_logs->document();
    if (doc->blockCount() > 50) {
        QTextCursor cursor(doc);
        cursor.movePosition(QTextCursor::Start);
        cursor.select(QTextCursor::BlockUnderCursor);
        cursor.removeSelectedText();
        cursor.deleteChar(); // 删除换行符
    }
    
    // 自动滚动到底部
    QTextCursor cursor = ui->textEdit_logs->textCursor();
    cursor.movePosition(QTextCursor::End);
    ui->textEdit_logs->setTextCursor(cursor);
    
    // 在控制台也输出
    qDebug() << logEntry;
}

// 天气相关槽函数
void MainWindow::onWeatherDataUpdated()
{
    if (!m_weatherManager) return;
    
    WeatherManager::WeatherData data = m_weatherManager->getCurrentWeatherData();
    if (!data.isValid) return;
    
    // 更新天气信息显示
    ui->label_weather->setText(data.weather);
    ui->label_temperature->setText(data.temperature);
    ui->label_humidity->setText(data.humidity);
    ui->label_wind->setText(QString("%1 %2").arg(data.windSpeed, data.windDirection));
    
    // 设置天气图标颜色
    if (data.weather.contains("晴")) {
        ui->label_weather->setStyleSheet("QLabel { color: #f39c12; font-weight: bold; }");
    } else if (data.weather.contains("雨")) {
        ui->label_weather->setStyleSheet("QLabel { color: #3498db; font-weight: bold; }");
    } else if (data.weather.contains("云")) {
        ui->label_weather->setStyleSheet("QLabel { color: #95a5a6; font-weight: bold; }");
    } else {
        ui->label_weather->setStyleSheet("QLabel { color: #2c3e50; font-weight: bold; }");
    }
    
    logMessage(QString("天气数据更新: %1, %2, %3, %4")
               .arg(data.weather, data.temperature, data.humidity, data.windSpeed));
}

void MainWindow::onCityChanged()
{
    if (!m_weatherManager) return;
    
    QString selectedCity = ui->comboBox_city->currentText();
    int currentIndex = ui->comboBox_city->currentIndex();
    int itemCount = ui->comboBox_city->count();
    
    QString currentCity = m_weatherManager->getCurrentCity();
    
    logMessage(QString("城市选择变化: %1 -> %2").arg(currentCity, selectedCity));
    logMessage(QString("ComboBox当前索引: %1, 项目数: %2").arg(currentIndex).arg(itemCount));
    
    if (!selectedCity.isEmpty() && selectedCity != currentCity) {
        m_weatherManager->setCity(selectedCity);
        logMessage("切换城市: " + selectedCity);
        
        // 强制刷新显示
        ui->comboBox_city->update();
        ui->comboBox_city->repaint();
    }
}

void MainWindow::onCitySliderChanged(int value)
{
    if (!m_weatherManager) return;
    
    // 确保值在有效范围内
    if (value < 0 || value >= ui->comboBox_city->count()) return;
    
    // 获取对应的城市名称
    QString cityName = ui->comboBox_city->itemText(value);
    if (cityName.isEmpty()) return;
    
    // 更新显示标签
    ui->label_city_display->setText("当前: " + cityName);
    
    // 同步ComboBox选择（这会触发城市切换）
    if (ui->comboBox_city->currentText() != cityName) {
        // 暂时断开ComboBox信号，避免循环触发
        ui->comboBox_city->blockSignals(true);
        ui->comboBox_city->setCurrentText(cityName);
        ui->comboBox_city->blockSignals(false);
        
        // 手动触发城市切换
        if (m_weatherManager) {
            m_weatherManager->setCity(cityName);
            logMessage("通过滑动栏切换城市: " + cityName);
        }
    }
}

void MainWindow::onWeatherError(const QString &error)
{
    logMessage("天气数据错误: " + error);
    ui->label_weather->setText("获取失败");
    ui->label_weather->setStyleSheet("QLabel { color: #e74c3c; font-weight: bold; }");
}

// 🆕 智能语音交互处理函数
void MainWindow::processVoiceCommand(const QString &text)
{
    // 检查输入文本是否有效
    QString cleanText = text.trimmed();
    if (cleanText.isEmpty() || cleanText == "百度识别: " || cleanText.endsWith("百度识别: ")) {
        return; // 不处理空的或无效的识别结果
    }
    
    QString lowerText = cleanText.toLower();
    
    // 🎵 如果正在播放音乐且不是音乐控制指令，暂停音乐进行对话
    bool isMusicControlCommand = lowerText.contains("播放音乐") || lowerText.contains("放音乐") || 
                                lowerText.contains("听音乐") || lowerText.contains("play music") ||
                                lowerText.contains("播放歌曲") || lowerText.contains("放歌") || 
                                lowerText.contains("听歌") || lowerText.contains("播放晴天") ||
                                lowerText.contains("晴天") || 
                                lowerText.contains("关闭音乐") || lowerText.contains("停止播放") || 
                                lowerText.contains("停止音乐") || lowerText.contains("stop music") ||
                                lowerText.contains("暂停音乐") || lowerText.contains("pause music") ||
                                lowerText.contains("切换音乐") || lowerText.contains("换首歌") || 
                                lowerText.contains("下一首") || lowerText.contains("next song") ||
                                lowerText.contains("change music") || lowerText.contains("换歌") ||
                                lowerText.contains("切歌") ||
                                lowerText.contains("增大音量") || lowerText.contains("调大音量") ||
                                lowerText.contains("减小音量") || lowerText.contains("调小音量") ||
                                lowerText.contains("音量大") || lowerText.contains("音量小") ||
                                lowerText.contains("volume up") || lowerText.contains("volume down");
    
    if (m_isMusicPlaying && !isMusicControlCommand) {
        // 暂停音乐进行对话
        pauseMusicForConversation();
    }
    
    // 🎯 智能情感分析 - 基于语音内容自动识别情感状态
    QString detectedEmotion = analyzeEmotionFromText(cleanText);
    if (!detectedEmotion.isEmpty()) {
        handleEmotionControl(detectedEmotion);
        return;
    }
    
    // 检查是否为天气查询 - 扩展关键词
    if (lowerText.contains("天气") || lowerText.contains("weather") || 
        lowerText.contains("温度") || lowerText.contains("下雨") || 
        lowerText.contains("晴天") || lowerText.contains("多云") ||
        lowerText.contains("冷不冷") || lowerText.contains("热不热") ||
        lowerText.contains("暖不暖") || lowerText.contains("凉快") ||
        lowerText.contains("气温") || lowerText.contains("外面")) {
        handleWeatherQuery(text);
    }
    // 检查是否为时间查询
    else if (lowerText.contains("时间") || lowerText.contains("几点") || 
             lowerText.contains("现在") || lowerText.contains("time")) {
        handleTimeQuery();
    }
    // 检查是否为离家回家指令
    else if (lowerText.contains("我要离开家咯") || lowerText.contains("我要出门了") || 
             lowerText.contains("要出门") || lowerText.contains("要离开") ||
             lowerText.contains("leaving home") || lowerText.contains("going out") ||
             lowerText.contains("去上班了") || lowerText.contains("上班去了") ||
             lowerText.contains("去工作") || lowerText.contains("going to work") ||
             lowerText.contains("去买东西") || lowerText.contains("去购物") ||
             lowerText.contains("去超市") || lowerText.contains("shopping") ||
             lowerText.contains("买菜") || lowerText.contains("去旅行") ||
             lowerText.contains("去旅游") || lowerText.contains("出差") ||
             lowerText.contains("travel") || lowerText.contains("trip")) {
        handleLeavingHomeCommand(text);
    }
    // 检查是否为回家指令
    else if (lowerText.contains("我回家啦") || lowerText.contains("我回来了") || 
             lowerText.contains("回家了") || lowerText.contains("i'm home") ||
             lowerText.contains("i'm back")) {
        handleComingHomeCommand(text);
    }
    // 检查是否为音乐播放控制
    else if (lowerText.contains("播放音乐") || lowerText.contains("放音乐") || 
             lowerText.contains("听音乐") || lowerText.contains("play music") ||
             lowerText.contains("播放歌曲") || lowerText.contains("放歌") || 
             lowerText.contains("听歌") || lowerText.contains("播放晴天") ||
             lowerText.contains("晴天") || 
             lowerText.contains("关闭音乐") || lowerText.contains("停止播放") || 
             lowerText.contains("停止音乐") || lowerText.contains("stop music") ||
             lowerText.contains("暂停音乐") || lowerText.contains("pause music") ||
             lowerText.contains("切换音乐") || lowerText.contains("换首歌") || 
             lowerText.contains("下一首") || lowerText.contains("next song") ||
             lowerText.contains("change music") || lowerText.contains("换歌") ||
             lowerText.contains("切歌") ||
             lowerText.contains("增大音量") || lowerText.contains("调大音量") ||
             lowerText.contains("减小音量") || lowerText.contains("调小音量") ||
             lowerText.contains("音量大") || lowerText.contains("音量小") ||
             lowerText.contains("volume up") || lowerText.contains("volume down")) {
        handleMusicCommand(text);
    }
    // 检查是否为LED控制指令
    else if (lowerText.contains("开灯") || lowerText.contains("打开灯") || 
             lowerText.contains("开启led") || lowerText.contains("turn on led") ||
             lowerText.contains("led on") || lowerText.contains("关灯") ||
             lowerText.contains("关闭灯") || lowerText.contains("关闭led") ||
             lowerText.contains("turn off led") || lowerText.contains("led off") ||
             lowerText.contains("切换灯") || lowerText.contains("反转led") ||
             lowerText.contains("toggle led")) {
        handleLedCommand(text);
    }
    // 检查是否为设备控制
    else if (lowerText.contains("打开") || lowerText.contains("关闭") || 
             lowerText.contains("控制") || lowerText.contains("设备")) {
        QString response = "好的，我已经收到您的设备控制指令。不过当前系统主要专注于情感交互功能。";
        speakResponse(response);
    }
    // 其他一般对话
    else {
        handleGeneralChat(text);
    }
}

void MainWindow::handleWeatherQuery(const QString &text)
{
    if (!m_weatherManager) {
        speakResponse("抱歉，天气系统暂时不可用。");
        return;
    }
    
    QString lowerText = text.toLower();
    QString targetCity = m_weatherManager->getCurrentCity(); // 默认当前城市
    
    // 检查是否指定了城市
    QStringList supportedCities = m_weatherManager->getSupportedCities();
    for (const QString &city : supportedCities) {
        if (text.contains(city)) {
            targetCity = city;
            // 如果不是当前城市，切换到指定城市
            if (targetCity != m_weatherManager->getCurrentCity()) {
                m_weatherManager->setCity(targetCity);
                ui->comboBox_city->setCurrentText(targetCity);
            }
            break;
        }
    }
    
    // 获取天气数据并生成统一回应 - 使用auto避免类型声明
    auto weather = m_weatherManager->getCurrentWeatherData();
    if (weather.isValid) {
        // 🔧 统一天气回复格式，避免重复
        QString response = QString("%1今天天气%2，温度%3，湿度%4，%5%6")
                          .arg(targetCity, weather.weather, weather.temperature, 
                               weather.humidity, weather.windSpeed, weather.windDirection);
        
        // 根据天气条件统一添加建议
        if (weather.weather.contains("雨")) {
            response += "，建议带伞出行";
        } else if (weather.weather.contains("晴")) {
            response += "，天气不错适合外出";
        } else if (weather.weather.contains("多云")) {
            response += "，天气比较舒适";
        }
        response += "。";
        
        speakResponse(response);
        
        // 自动切换到天气页面
        switchToPage(2);
    } else {
        speakResponse("抱歉，暂时无法获取天气信息，请稍后再试。");
    }
}

// 🎯 智能情感分析函数 - 基于文本内容识别用户情感状态
QString MainWindow::analyzeEmotionFromText(const QString &text)
{
    QString lowerText = text.toLower();
    
    // 🟡 开心/积极情感关键词
    QStringList happyKeywords = {
        "开心", "高兴", "快乐", "兴奋", "愉快", "满意", "幸福", "舒服", "爽",
        "happy", "excited", "joyful", "pleased", "glad", "cheerful",
        "哈哈", "嘻嘻", "太好了", "真棒", "不错", "厉害", "成功了", "达成了",
        "喜欢", "爱", "棒", "赞", "优秀", "完美", "顺利", "如意"
    };
    
    // 🔵 伤心/消极情感关键词  
    QStringList sadKeywords = {
        "伤心", "难过", "悲伤", "沮丧", "失落", "郁闷", "低落", "痛苦", "哭",
        "sad", "upset", "depressed", "disappointed", "down", "heartbroken",
        "呜呜", "不开心", "心情不好", "失败了", "完蛋了", "糟糕", "倒霉",
        "想哭", "心疼", "委屈", "受伤", "孤独", "空虚", "绝望"
    };
    
    // 🔴 愤怒情感关键词
    QStringList angryKeywords = {
        "生气", "愤怒", "恼火", "暴躁", "烦躁", "气死了", "火大", "怒",
        "angry", "mad", "furious", "irritated", "pissed", "annoyed",
        "该死", "可恶", "讨厌", "烦人", "受不了", "忍无可忍", "气人",
        "混蛋", "垃圾", "破", "坏", "恶心", "厌恶"
    };
    
    // 🟠 惊讶情感关键词
    QStringList surprisedKeywords = {
        "惊讶", "震惊", "吃惊", "意外", "没想到", "怎么可能", "不敢相信",
        "surprised", "shocked", "amazed", "astonished", "incredible",
        "哇", "天哪", "我的天", "不会吧", "真的吗", "厉害了", "太神奇了",
        "突然", "忽然", "竟然", "居然", "原来", "发现"
    };
    
    // 🟢 恐惧情感关键词
    QStringList fearKeywords = {
        "害怕", "恐惧", "紧张", "担心", "焦虑", "忧虑", "不安", "怕",
        "afraid", "scared", "nervous", "worried", "anxious", "fearful",
        "可怕", "恐怖", "吓人", "危险", "威胁", "不敢", "胆小"
    };
    
    // 计算各种情感的权重
    int happyScore = 0, sadScore = 0, angryScore = 0, surprisedScore = 0, fearScore = 0;
    
    // 统计各类情感关键词出现次数
    for (const QString &keyword : happyKeywords) {
        if (lowerText.contains(keyword)) happyScore++;
    }
    for (const QString &keyword : sadKeywords) {
        if (lowerText.contains(keyword)) sadScore++;
    }
    for (const QString &keyword : angryKeywords) {
        if (lowerText.contains(keyword)) angryScore++;
    }
    for (const QString &keyword : surprisedKeywords) {
        if (lowerText.contains(keyword)) surprisedScore++;
    }
    for (const QString &keyword : fearKeywords) {
        if (lowerText.contains(keyword)) fearScore++;
    }
    
    // 🔍 情感上下文分析 - 检查否定词
    bool hasNegation = lowerText.contains("不") || lowerText.contains("没") || 
                      lowerText.contains("别") || lowerText.contains("非") ||
                      lowerText.contains("not") || lowerText.contains("no");
    
    // 如果有否定词，调整情感分数
    if (hasNegation) {
        // "不开心" -> 伤心, "不害怕" -> 开心
        if (happyScore > 0) {
            sadScore += happyScore;
            happyScore = 0;
        }
        if (fearScore > 0) {
            happyScore += fearScore;
            fearScore = 0;
        }
    }
    
    // 找出得分最高的情感
    int maxScore = qMax(qMax(qMax(qMax(happyScore, sadScore), angryScore), surprisedScore), fearScore);
    
    if (maxScore > 0) {
        if (happyScore == maxScore) return "happy";
        if (sadScore == maxScore) return "sad";
        if (angryScore == maxScore) return "angry";
        if (surprisedScore == maxScore) return "surprised";
        if (fearScore == maxScore) return "fear";
    }
    
    return ""; // 没有明确的情感倾向
}

void MainWindow::handleEmotionControl(const QString &emotion)
{
    QString response;
    
    if (emotion == "happy") {
        onSetHappyEmotion();
        response = "好的，我现在很开心！让我们一起保持愉快的心情吧！😊";
    } else if (emotion == "sad") {
        onSetSadEmotion();
        response = "我理解您的心情，让我陪着您一起。希望您能很快好起来。😢";
    } else if (emotion == "angry") {
        onSetAngryEmotion();
        response = "我能感受到您的情绪，让我们试着冷静下来，深呼吸一下。😤";
    } else if (emotion == "surprised") {
        onSetSurprisedEmotion();
        response = "哇！真的很令人惊讶呢！😲";
    } else if (emotion == "fear") {
        // 添加恐惧表情处理
        if (m_emotionController) {
            m_currentEmotion = "fear";
            updateEmotionDisplay();
            m_emotionController->setEmotion("fear", 100);
        }
        response = "别害怕，我在这里陪着您。一切都会好起来的。😰";
        logMessage("设置表情: 恐惧");
    } else if (emotion == "neutral") {
        onSetNeutralEmotion();
        response = "好的，我现在恢复到平静的状态了。😐";
    }
    
    speakResponse(response);
    
    // 自动切换到表情页面
    switchToPage(1);
    
    // 记录情感识别日志
    logMessage(QString("🎯 智能情感识别: %1 -> %2").arg(emotion).arg(response));
}

void MainWindow::handleTimeQuery()
{
    QDateTime now = QDateTime::currentDateTime();
    QString timeStr = now.toString("现在是yyyy年MM月dd日，hh点mm分");
    QString weekStr = now.toString("dddd");
    
    // 转换星期为中文
    QStringList weekDays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
    int dayIndex = now.date().dayOfWeek() - 1;
    if (dayIndex >= 0 && dayIndex < weekDays.size()) {
        weekStr = weekDays[dayIndex];
    }
    
    QString response = timeStr + "，" + weekStr + "。";
    
    // 根据时间添加问候
    int hour = now.time().hour();
    if (hour >= 6 && hour < 9) {
        response += "早上好！";
    } else if (hour >= 9 && hour < 12) {
        response += "上午好！";
    } else if (hour >= 12 && hour < 14) {
        response += "中午好！";
    } else if (hour >= 14 && hour < 18) {
        response += "下午好！";
    } else if (hour >= 18 && hour < 22) {
        response += "晚上好！";
    } else {
        response += "夜深了，注意休息哦！";
    }
    
    speakResponse(response);
}

void MainWindow::handleGeneralChat(const QString &text)
{
    QString response = generateSmartResponse(text);
    speakResponse(response);
}

QString MainWindow::generateSmartResponse(const QString &command)
{
    // 使用新的情感语言库
    ChatDB::ChatResponse chatResp = ChatDB::getResponse(command);
    if (chatResp.isValid()) {
        // 🆕 根据回复的情感类型发送对应的表情指令
        sendEmotionCommand(chatResp.emotion);
        return chatResp.text;
    }
    
    QString lowerCmd = command.toLower();
    
    // 问候语回应
    if (lowerCmd.contains("你好") || lowerCmd.contains("hello") || lowerCmd.contains("hi")) {
        return "你好！我是RK3588智能情感交互系统，很高兴和您对话！";
    }
    
    // 系统介绍
    if (lowerCmd.contains("你是谁") || lowerCmd.contains("介绍") || lowerCmd.contains("功能")) {
        return "我是RK3588智能情感交互系统，我可以进行语音对话、表情交互、天气查询等功能。您可以问我天气情况，或者让我改变表情状态。";
    }
    
    // 感谢回应
    if (lowerCmd.contains("谢谢") || lowerCmd.contains("thanks") || lowerCmd.contains("thank")) {
        return "不客气！能为您服务我很开心！";
    }
    
    // 再见
    if (lowerCmd.contains("再见") || lowerCmd.contains("bye") || lowerCmd.contains("goodbye")) {
        return "再见！期待下次与您对话！";
    }
    
    // 夸奖
    if (lowerCmd.contains("很棒") || lowerCmd.contains("不错") || lowerCmd.contains("good") || lowerCmd.contains("great")) {
        return "谢谢您的夸奖！我会继续努力为您提供更好的服务！";
    }
    
    // 询问状态
    if (lowerCmd.contains("怎么样") || lowerCmd.contains("如何") || lowerCmd.contains("状态")) {
        return "我现在状态很好！所有系统都运行正常，随时准备为您服务！";
    }
    
    // 自我认知及"你是..."问题
    if (lowerCmd.contains("你是谁") || lowerCmd.contains("你是什么") || lowerCmd.contains("who are you")) {
        return "我是跑在RK3588上的智能情感交互系统，一个由 Qt + AI 驱动的语音助手。";
    }

    if (lowerCmd.contains("你是人类") || lowerCmd.contains("你是机器人") || lowerCmd.contains("are you human")) {
        return "我并不是人类，而是一名虚拟助手，但我会尽力用最自然的方式与您交流。";
    }

    // "你在干什么"
    if (lowerCmd.contains("你在干什么") || lowerCmd.contains("what are you doing")) {
        return "我正专注地等待您的指令，随时准备提供帮助！";
    }

    // 带有侮辱性质的句子简单过滤并礼貌回应
    QStringList rudeWords = {"猪", "笨", "傻", "蠢", "垃圾", "废物", "猪头"};
    for (const QString &word : rudeWords) {
        if (lowerCmd.contains(word)) {
            return "我理解您的情绪，但请保持礼貌，让我们积极交流。";
        }
    }

    // 当用户表示迷茫或"怎么办"时给出安慰
    if (lowerCmd.contains("怎么办") || lowerCmd.contains("help")) {
        return "或许您可以先告诉我遇到了什么问题，我会尽力给予建议或提供信息。";
    }

    // 如果检测到问句但未匹配任何知识点，做通用回答
    if (lowerCmd.endsWith("?") || lowerCmd.contains("吗")) {
        return "这是个好问题，我会持续学习，争取下次给您更好的答案！";
    }
    
    // 🔧 统一默认回应，避免重复
    return "我理解您的意思。您可以问我'今天天气怎么样'、说'我很开心'来改变表情，或者询问'现在几点了'。";
}

void MainWindow::speakResponse(const QString &response)
{
    if (m_speechManager) {
        // 🔧 一问一答模式：显示正在回应状态
        ui->label_conversation_status->setText("正在回应...");
        ui->label_conversation_status->setStyleSheet("QLabel { color: #FF9800; font-weight: bold; }");
        
        // 在识别结果中显示AI回应
        QString timestamp = QDateTime::currentDateTime().toString("hh:mm:ss");
        QString aiResponse = QString("[%1] 🤖 AI: %2").arg(timestamp, response);
        ui->textEdit_conversation->append(aiResponse);
        
        // 自动滚动到底部
        QTextCursor cursor = ui->textEdit_conversation->textCursor();
        cursor.movePosition(QTextCursor::End);
        ui->textEdit_conversation->setTextCursor(cursor);
        ui->textEdit_conversation->ensureCursorVisible();
        
        // 语音合成回应
        m_speechManager->synthesizeText(response);
        
        // 记录日志
        logMessage("AI回应: " + response);
    }
}

// 🆕 情感指令发送函数 - 将ChatDB情感类型转换为EmotionController情感类型
void MainWindow::sendEmotionCommand(ChatDB::EmotionType emotion)
{
    if (!m_emotionController) {
        logMessage("情感控制器未初始化，无法发送情感指令");
        return;
    }
    
    // 映射ChatDB情感类型到EmotionController情感类型
    EmotionController::EmotionType controllerEmotion;
    int intensity = 70; // 默认强度
    
    switch (emotion) {
        case ChatDB::NEUTRAL:
            controllerEmotion = EmotionController::Neutral;
            intensity = 50;
            break;
        case ChatDB::HAPPY:
            controllerEmotion = EmotionController::Happy;
            intensity = 80;
            break;
        case ChatDB::SAD:
            controllerEmotion = EmotionController::Sad;
            intensity = 60;
            break;
        case ChatDB::ANGRY:
            controllerEmotion = EmotionController::Angry;
            intensity = 85;
            break;
        case ChatDB::SURPRISED:
            controllerEmotion = EmotionController::Surprised;
            intensity = 75;
            break;
        case ChatDB::FEAR:
            controllerEmotion = EmotionController::Fear;
            intensity = 65;
            break;
        case ChatDB::SLEEP:
            controllerEmotion = EmotionController::Sleep;
            intensity = 10;
            break;
        default:
            controllerEmotion = EmotionController::Neutral;
            intensity = 50;
            break;
    }
    
    // 发送情感指令到设备
    m_emotionController->setEmotion(controllerEmotion, intensity);
    
    // 记录日志
    QString emotionName;
    switch (emotion) {
        case ChatDB::NEUTRAL: emotionName = "NEUTRAL"; break;
        case ChatDB::HAPPY: emotionName = "HAPPY"; break;
        case ChatDB::SAD: emotionName = "SAD"; break;
        case ChatDB::ANGRY: emotionName = "ANGRY"; break;
        case ChatDB::SURPRISED: emotionName = "SURPRISED"; break;
        case ChatDB::FEAR: emotionName = "FEAR"; break;
        case ChatDB::SLEEP: emotionName = "SLEEP"; break;
        default: emotionName = "UNKNOWN"; break;
    }
    
    logMessage(QString("发送情感指令: %1 (强度: %2)").arg(emotionName).arg(intensity));
}

// 摄像头相关槽函数
void MainWindow::onCameraStart()
{
    if (!m_cameraManager) {
        logMessage("摄像头管理器未初始化");
        return;
    }
    
    // 启动摄像头
    ui->pushButton_camera_start->setEnabled(false);
    ui->label_camera_status->setText("状态: 启动中...");
    ui->label_camera_status->setStyleSheet("QLabel { color: #f39c12; font-size: 8px; font-weight: bold; }");
    
    logMessage("正在启动摄像头...");
    
    bool success = m_cameraManager->startCamera();
    if (success) {
        ui->pushButton_camera_stop->setEnabled(true);
        ui->pushButton_camera_snapshot->setEnabled(true);
        
        // 更新分辨率显示
        ui->label_camera_resolution->setText(QString("分辨率: %1").arg(m_cameraManager->getResolution()));
        
        logMessage("摄像头启动成功");
    } else {
        ui->pushButton_camera_start->setEnabled(true);
        ui->label_camera_status->setText("状态: 启动失败");
        ui->label_camera_status->setStyleSheet("QLabel { color: #e74c3c; font-size: 8px; font-weight: bold; }");
        logMessage("摄像头启动失败");
    }
}

void MainWindow::onCameraStop()
{
    if (!m_cameraManager) {
        logMessage("摄像头管理器未初始化");
        return;
    }
    
    // 停止摄像头
    m_cameraManager->stopCamera();
    
    ui->pushButton_camera_start->setEnabled(true);
    ui->pushButton_camera_stop->setEnabled(false);
    ui->pushButton_camera_snapshot->setEnabled(false);
    
    ui->label_camera_status->setText("状态: 离线");
    ui->label_camera_status->setStyleSheet("QLabel { color: #e74c3c; font-size: 8px; font-weight: bold; }");
    ui->label_camera_fps->setText("帧率: 0 FPS");
    
    // 清除画面显示
    ui->label_camera_display->clear();
    ui->label_camera_display->setText("摄像头画面显示区域");
    ui->label_camera_display->setStyleSheet(
        "QLabel {"
        "    background-color: #1e1e1e;"
        "    border: 2px solid #3498db;"
        "    border-radius: 4px;"
        "    color: #ecf0f1;"
        "    font-size: 12px;"
        "    font-weight: bold;"
        "}"
    );
    
    logMessage("摄像头已停止");
}

void MainWindow::onCameraSnapshot()
{
    if (!m_cameraManager) {
        logMessage("摄像头管理器未初始化");
        return;
    }
    
    if (!m_cameraManager->isActive()) {
        logMessage("摄像头未启动，无法拍照");
        return;
    }
    
    // 拍照功能
    logMessage("正在拍照...");
    m_cameraManager->captureImage();
}

void MainWindow::onCameraFrameReady()
{
    // 处理摄像头帧数据
    // 这里可以添加实际的摄像头帧处理逻辑
}

void MainWindow::onCameraError(const QString &error)
{
    ui->label_camera_status->setText("状态: 错误");
    ui->label_camera_status->setStyleSheet("QLabel { color: #e74c3c; font-size: 8px; font-weight: bold; }");
    ui->pushButton_camera_start->setEnabled(true);
    ui->pushButton_camera_stop->setEnabled(false);
    ui->pushButton_camera_snapshot->setEnabled(false);
    
    logMessage("摄像头错误: " + error);
}

// 缺少的函数实现
void MainWindow::on_testCameraButton_clicked()
{
    qDebug() << "Camera test button clicked";
    logMessage("摄像头测试按钮被点击");
    if (m_cameraManager) {
        if (m_cameraManager->isActive()) {
            onCameraStop();
        } else {
            onCameraStart();
        }
    }
}

void MainWindow::on_testMicrophoneButton_clicked()
{
    qDebug() << "Microphone test button clicked";
    logMessage("麦克风测试按钮被点击");
    // 临时实现 - 可以添加麦克风测试逻辑
}

void MainWindow::on_testSpeakerButton_clicked()
{
    qDebug() << "Speaker test button clicked";
    logMessage("扬声器测试按钮被点击");
    // 播放测试音频
    if (m_speechManager) {
        m_speechManager->synthesizeText("扬声器测试，您能听到我的声音吗？");
    }
}

void MainWindow::onHotspotError(const QString &error)
{
    qDebug() << "Hotspot error:" << error;
    logMessage("热点错误: " + error);
}

void MainWindow::onHotspotDeviceDisconnected(const QString &device)
{
    qDebug() << "Device disconnected:" << device;
    logMessage("设备断开连接: " + device);
}

void MainWindow::onHotspotDeviceConnected()
{
    qDebug() << "Device connected to hotspot";
    logMessage("设备已连接到热点");
}

void MainWindow::onHotspotStateChanged(bool enabled)
{
    qDebug() << "Hotspot state changed:" << enabled;
    logMessage(QString("热点状态改变: %1").arg(enabled ? "启用" : "禁用"));
}

void MainWindow::onHotspotConfigChanged()
{
    qDebug() << "Hotspot config changed";
    logMessage("热点配置已更改");
}

void MainWindow::onStopHotspot()
{
    qDebug() << "Stop hotspot clicked";
    logMessage("停止热点按钮被点击");
    if (m_hotspotController) {
        m_hotspotController->stopHotspot();
    }
}

void MainWindow::onStartHotspot()
{
    qDebug() << "Start hotspot clicked";
    logMessage("启动热点按钮被点击");
    if (m_hotspotController) {
        m_hotspotController->startHotspot();
    }
}

void MainWindow::stopRecording()
{
    qDebug() << "Stop recording called";
    logMessage("停止录音被调用");
    // 临时实现
}

void MainWindow::resetIdleTimer()
{
    if (m_idleTimer) {
        m_idleTimer->start(IDLE_TIMEOUT_MS);
    }
}

void MainWindow::onIdleTimeout()
{
    logMessage("长时间无语音交互，进入休眠模式");
    if (m_emotionController) {
        // 使用专门的休眠模式
        m_emotionController->setSleepMode();
    }
    ui->label_conversation_status->setText("💤 已进入休眠模式，轻触或说话唤醒");
    ui->label_conversation_status->setStyleSheet("QLabel { color: #7f8c8d; font-weight: bold; }");
}

// 🎨 样式美化实现方法
void MainWindow::applyModernStyles()
{
    // 使用嵌入式现代化样式
    QString modernStyle = R"(
/* =======================================================
   RK3588 智能交互系统 - 现代化样式表
   ======================================================= */

/* ======================= 全局样式 ======================= */
QMainWindow {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #f8fafc, stop:1 #e2e8f0);
    color: #334155;
    font-family: "Microsoft YaHei", "SimHei", Arial, sans-serif;
}

/* ======================= 标题栏样式 ======================= */
#label_header_title {
    font-size: 64px;
    font-weight: 900;
    color: white;
    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,
        stop:0 #6366f1, stop:0.5 #8b5cf6, stop:1 #06b6d4);
    padding: 40px 20px;
    border-radius: 0px;
    border-bottom: 5px solid rgba(255,255,255,0.3);
}

/* ======================= 主要按钮样式 ======================= */
QPushButton {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #3b82f6, stop:1 #1d4ed8);
    border: none;
    border-radius: 16px;
    padding: 25px 35px;
    color: white;
    font-weight: bold;
    font-size: 38px;
    min-height: 80px;
}

QPushButton:hover {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #2563eb, stop:1 #1e40af);
}

QPushButton:pressed {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #1d4ed8, stop:1 #1e3a8a);
}

QPushButton:disabled {
    background: #94a3b8;
    color: #cbd5e1;
}

/* ======================= 底部导航栏 ======================= */
#navWidget {
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #1e293b, stop:1 #0f172a);
    border-top: 3px solid #334155;
    min-height: 160px;
    max-height: 160px;
}

#navWidget QPushButton {
    background-color: transparent;
    border: none;
    color: #94a3b8;
    text-align: center;
    padding: 20px 10px;
    font-size: 32px;
    font-weight: bold;
    border-radius: 12px;
    margin: 8px 4px;
}

#navWidget QPushButton:hover {
    background: rgba(59, 130, 246, 0.2);
    color: #e2e8f0;
}

#navWidget QPushButton:checked {
    color: white;
    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
        stop:0 #3b82f6, stop:1 #1d4ed8);
    border: 2px solid #60a5fa;
}

/* ======================= 标签样式 ======================= */
QLabel {
    color: #475569;
    font-size: 36px;
    background-color: transparent;
    padding: 8px;
}

/* ======================= 输入框样式 ======================= */
QTextEdit, QLineEdit {
    background: white;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    padding: 15px;
    font-size: 34px;
    color: #334155;
}

QTextEdit:focus, QLineEdit:focus {
    border: 2px solid #3b82f6;
    outline: none;
}

/* ======================= 滚动条样式 ======================= */
QScrollBar:vertical {
    background: rgba(241, 245, 249, 0.8);
    width: 12px;
    border-radius: 6px;
    margin: 0;
}

QScrollBar::handle:vertical {
    background: #94a3b8;
    border-radius: 6px;
    min-height: 30px;
}

QScrollBar::handle:vertical:hover {
    background: #64748b;
}

QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
    height: 0;
}
    )";
    
    this->setStyleSheet(modernStyle);
    
    // 应用特定按钮样式
    setupButtonStyles();
    
    // 应用特定标签样式
    setupLabelStyles();
}

void MainWindow::setupButtonStyles()
{
    // 为重要功能按钮设置特殊颜色
    
    // 成功类按钮（绿色）
    QStringList successButtons = {
        "pushButton_start_conversation", "pushButton_camera_start", 
        "pushButton_start_hotspot", "pushButton_happy"
    };
    
    for (const QString &buttonName : successButtons) {
        QPushButton *btn = this->findChild<QPushButton*>(buttonName);
        if (btn) {
            btn->setStyleSheet(
                "QPushButton {"
                "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                "        stop:0 #10b981, stop:1 #059669);"
                "    border: none; border-radius: 16px; padding: 25px 35px;"
                "    color: white; font-weight: bold; font-size: 38px; min-height: 80px;"
                "}"
                "QPushButton:hover {"
                "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                "        stop:0 #059669, stop:1 #047857);"
                "}"
            );
        }
    }
    
    // 危险类按钮（红色）
    QStringList dangerButtons = {
        "pushButton_stop_reply", "pushButton_camera_stop", 
        "pushButton_stop_hotspot", "pushButton_angry"
    };
    
    for (const QString &buttonName : dangerButtons) {
        QPushButton *btn = this->findChild<QPushButton*>(buttonName);
        if (btn) {
            btn->setStyleSheet(
                "QPushButton {"
                "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                "        stop:0 #ef4444, stop:1 #dc2626);"
                "    border: none; border-radius: 16px; padding: 25px 35px;"
                "    color: white; font-weight: bold; font-size: 38px; min-height: 80px;"
                "}"
                "QPushButton:hover {"
                "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                "        stop:0 #dc2626, stop:1 #b91c1c);"
                "}"
            );
        }
    }
    
    // 警告类按钮（橙色）
    QStringList warningButtons = {
        "pushButton_test_tts", "pushButton_reconnect_device", 
        "pushButton_reconnect", "pushButton_surprised"
    };
    
    for (const QString &buttonName : warningButtons) {
        QPushButton *btn = this->findChild<QPushButton*>(buttonName);
        if (btn) {
            btn->setStyleSheet(
                "QPushButton {"
                "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                "        stop:0 #f59e0b, stop:1 #d97706);"
                "    border: none; border-radius: 16px; padding: 25px 35px;"
                "    color: white; font-weight: bold; font-size: 38px; min-height: 80px;"
                "}"
                "QPushButton:hover {"
                "    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,"
                "        stop:0 #d97706, stop:1 #b45309);"
                "}"
            );
        }
    }
}

void MainWindow::setupLabelStyles()
{
    // 状态指示标签样式
    QStringList statusLabels = {
        "label_conversation_status", "label_device_status", 
        "label_camera_status", "label_hotspot_status"
    };
    
    for (const QString &labelName : statusLabels) {
        QLabel *label = this->findChild<QLabel*>(labelName);
        if (label) {
            label->setStyleSheet(
                "QLabel {"
                "    color: #0f766e;"
                "    background: rgba(204, 251, 241, 0.8);"
                "    border: 1px solid #14b8a6;"
                "    border-radius: 12px;"
                "    padding: 15px 20px;"
                "    font-size: 32px;"
                "    margin: 10px 0;"
                "}"
            );
        }
    }
    
    // 页面标题样式
    QStringList titleLabels = {
        "label_speech_title", "label_emotion_title", 
        "label_sensor_title", "label_camera_title", "label_system_title"
    };
    
    for (const QString &labelName : titleLabels) {
        QLabel *label = this->findChild<QLabel*>(labelName);
        if (label) {
            label->setStyleSheet(
                "QLabel {"
                "    font-size: 48px; font-weight: bold; color: white;"
                "    background: qlineargradient(x1:0, y1:0, x2:1, y2:0,"
                "        stop:0 #667eea, stop:1 #764ba2);"
                "    padding: 30px; border-radius: 16px; margin-bottom: 20px;"
                "}"
            );
        }
    }
}

// 🎵 ================== 音乐播放相关函数实现 ==================

void MainWindow::handleMusicCommand(const QString &text)
{
    QString lowerText = text.toLower();
    
    // 检查是否为播放音乐的指令
    if (lowerText.contains("播放音乐") || lowerText.contains("放音乐") || 
        lowerText.contains("听音乐") || lowerText.contains("play music") ||
        lowerText.contains("播放歌曲") || lowerText.contains("放歌") || 
        lowerText.contains("听歌") || lowerText.contains("播放晴天") ||
        lowerText.contains("晴天")) {
        
        // 先检查音乐文件是否存在
        bool musicFileExists = false;
        QStringList possiblePaths = {
            "sunday.mp3",
            "../sunday.mp3", 
            "/code/sunday.mp3",
            QDir::currentPath() + "/sunday.mp3",
            QDir::currentPath() + "/../sunday.mp3"
        };
        
        for (const QString &path : possiblePaths) {
            if (QFile::exists(path)) {
                musicFileExists = true;
                break;
            }
        }
        
        // 根据文件是否存在给出不同的回复
        if (musicFileExists) {
            // 使用ChatDB获取成功播放的回复
            ChatDB::ChatResponse response = ChatDB::getResponse(text);
            if (response.isValid() && response.category == ChatDB::MUSIC) {
                speakResponse(response.text);
                sendEmotionCommand(response.emotion);
            }
            // 延迟播放音乐，等待语音回复完成（3秒后开始播放）
            QTimer::singleShot(3000, this, [this]() {
                startMusicPlayback();
            });
        } else {
            // 直接回复没有找到音乐文件
            speakResponse("抱歉，我没有找到音乐文件。请确认sunday.mp3文件是否存在。");
            sendEmotionCommand(ChatDB::SAD);
            logMessage("音乐播放请求失败：未找到音乐文件");
        }
    }
    // 检查是否为停止音乐的指令
    else if (lowerText.contains("关闭音乐") || lowerText.contains("停止播放") || 
             lowerText.contains("停止音乐") || lowerText.contains("stop music") ||
             lowerText.contains("暂停音乐") || lowerText.contains("pause music")) {
        
        // 使用ChatDB获取回复
        ChatDB::ChatResponse response = ChatDB::getResponse(text);
        if (response.isValid() && response.category == ChatDB::MUSIC) {
            speakResponse(response.text);
            sendEmotionCommand(response.emotion);
        }
        
        // 停止播放音乐
        stopMusicPlayback();
    }
    // 检查是否为切换音乐的指令
    else if (lowerText.contains("切换音乐") || lowerText.contains("换首歌") || 
             lowerText.contains("下一首") || lowerText.contains("next song") ||
             lowerText.contains("change music") || lowerText.contains("换歌") ||
             lowerText.contains("切歌")) {
        
        // 使用ChatDB获取回复
        ChatDB::ChatResponse response = ChatDB::getResponse(text);
        if (response.isValid() && response.category == ChatDB::MUSIC) {
            speakResponse(response.text);
            sendEmotionCommand(response.emotion);
        }
        
        // 延迟切换音乐，等待语音回复完成（3秒后开始播放）
        QTimer::singleShot(3000, this, [this]() {
            switchToNextMusic();
        });
    }
    // 检查是否为音量控制指令
    else if (lowerText.contains("增大音量") || lowerText.contains("调大音量") ||
             lowerText.contains("音量大") || lowerText.contains("volume up")) {
        
        // 增大音量
        adjustMusicVolume(true);
        speakResponse("好的，我已经为您调大音量。");
        sendEmotionCommand(ChatDB::HAPPY);
    }
    else if (lowerText.contains("减小音量") || lowerText.contains("调小音量") ||
             lowerText.contains("音量小") || lowerText.contains("volume down")) {
        
        // 减小音量
        adjustMusicVolume(false);
        speakResponse("好的，我已经为您调小音量。");
        sendEmotionCommand(ChatDB::HAPPY);
    }
    else {
        // 通用音乐相关回复
        handleGeneralChat(text);
    }
}

void MainWindow::startMusicPlayback()
{
    if (!m_musicPlayer) {
        logMessage("音乐播放器未初始化");
        return;
    }
    
    // 查找音乐文件路径（此时已确认文件存在）
    QStringList possiblePaths = {
        "sunday.mp3",
        "../sunday.mp3", 
        "/code/sunday.mp3",
        QDir::currentPath() + "/sunday.mp3",
        QDir::currentPath() + "/../sunday.mp3"
    };
    
    QString foundPath;
    for (const QString &path : possiblePaths) {
        if (QFile::exists(path)) {
            foundPath = path;
            m_currentMusicFile = path;
            break;
        }
    }
    
    if (foundPath.isEmpty()) {
        // 这种情况理论上不应该发生，因为调用前已经检查过
        logMessage("错误：音乐文件在调用时消失了");
        return;
    }
    
    // 如果正在播放，先停止
    if (m_isMusicPlaying) {
        m_musicPlayer->stop();
    }
    
    // 设置音乐文件并播放
    m_musicPlayer->setMedia(QUrl::fromLocalFile(foundPath));
    m_musicPlayer->play();
    
    m_isMusicPlaying = true;
    updateMusicUI();
    
    logMessage("开始播放音乐: " + foundPath);
}

void MainWindow::stopMusicPlayback()
{
    if (!m_musicPlayer) {
        return;
    }
    
    m_musicPlayer->stop();
    m_isMusicPlaying = false;
    updateMusicUI();
    
    logMessage("停止播放音乐");
}

void MainWindow::updateMusicUI()
{
    // 获取当前音乐文件名
    QString currentTitle = "sunday";  // 默认值
    if (!m_currentMusicFile.isEmpty()) {
        currentTitle = QFileInfo(m_currentMusicFile).baseName();
    }
    
    // 使用带标题的更新函数
    updateMusicUIWithTitle(currentTitle);
}

// 🎵 音乐播放器槽函数实现

void MainWindow::onPlayMusic()
{
    startMusicPlayback();
}

void MainWindow::onStopMusic()
{
    stopMusicPlayback();
}

void MainWindow::onMusicStateChanged()
{
    if (!m_musicPlayer) {
        return;
    }
    
    QMediaPlayer::State state = m_musicPlayer->state();
    switch (state) {
        case QMediaPlayer::PlayingState:
            m_isMusicPlaying = true;
            logMessage("🎵 音乐播放状态: 正在播放");
            break;
        case QMediaPlayer::PausedState:
            logMessage("🎵 音乐播放状态: 已暂停");
            break;
        case QMediaPlayer::StoppedState:
            m_isMusicPlaying = false;
            logMessage("🎵 音乐播放状态: 已停止");
            break;
    }
    
    updateMusicUI();
}

void MainWindow::onMusicPositionChanged(qint64 position)
{
    // 音乐播放位置变化，可以用于显示播放进度
    Q_UNUSED(position)
    // 这里可以添加进度条更新逻辑
}

void MainWindow::onMusicDurationChanged(qint64 duration)
{
    // 音乐总时长变化，可以用于初始化进度条
    Q_UNUSED(duration)
    // 这里可以添加总时长显示逻辑
}

void MainWindow::initializeMusicPlaylist()
{
    // 初始化音乐播放列表
    m_musicPlaylist.clear();
    m_currentMusicIndex = 0;
    
    // 检查各种可能的音乐文件
    QStringList possibleMusicFiles = {
        "sunday.mp3",
        "tts_jdUbSo.mp3", 
        "tts_pSrghE.mp3",
        "tts_ZvuLjH.mp3"
    };
    
    QStringList basePaths = {
        "",
        "../", 
        "/code/",
        QDir::currentPath() + "/",
        QDir::currentPath() + "/../"
    };
    
    // 搜索所有可能的音乐文件
    for (const QString &fileName : possibleMusicFiles) {
        for (const QString &basePath : basePaths) {
            QString fullPath = basePath + fileName;
            if (QFile::exists(fullPath) && !m_musicPlaylist.contains(fullPath)) {
                m_musicPlaylist.append(fullPath);
                logMessage("发现音乐文件: " + fullPath);
            }
        }
    }
    
    // 如果没有找到任何音乐文件，使用默认的sunday.mp3
    if (m_musicPlaylist.isEmpty()) {
        m_musicPlaylist.append("sunday.mp3");
        logMessage("未找到音乐文件，使用默认: sunday.mp3");
    }
    
    logMessage(QString("音乐播放列表初始化完成，共%1首歌曲").arg(m_musicPlaylist.size()));
}

void MainWindow::switchToNextMusic()
{
    if (m_musicPlaylist.isEmpty()) {
        // 如果播放列表为空，重新初始化
        initializeMusicPlaylist();
        if (m_musicPlaylist.isEmpty()) {
            logMessage("切换音乐失败：没有找到可以播放的音乐文件");
            return;
        }
    }
    
    // 切换到下一首
    m_currentMusicIndex = (m_currentMusicIndex + 1) % m_musicPlaylist.size();
    
    // 获取当前要播放的音乐文件
    QString nextMusicFile = m_musicPlaylist[m_currentMusicIndex];
    
    // 检查文件是否存在
    if (!QFile::exists(nextMusicFile)) {
        logMessage("警告：音乐文件不存在，尝试下一首: " + nextMusicFile);
        // 从播放列表中移除不存在的文件
        m_musicPlaylist.removeAt(m_currentMusicIndex);
        if (m_musicPlaylist.isEmpty()) {
            logMessage("切换音乐失败：所有音乐文件都无法访问");
            return;
        }
        // 调整索引并重试
        m_currentMusicIndex = m_currentMusicIndex % m_musicPlaylist.size();
        nextMusicFile = m_musicPlaylist[m_currentMusicIndex];
    }
    
    // 停止当前播放
    if (m_musicPlayer && m_isMusicPlaying) {
        m_musicPlayer->stop();
    }
    
    // 设置新的音乐文件
    m_currentMusicFile = nextMusicFile;
    
    // 开始播放新音乐
    if (m_musicPlayer) {
        m_musicPlayer->setMedia(QUrl::fromLocalFile(nextMusicFile));
        m_musicPlayer->play();
        m_isMusicPlaying = true;
        
        // 获取音乐文件名用于显示
        QString fileName = QFileInfo(nextMusicFile).baseName();
        updateMusicUIWithTitle(fileName);
        
        logMessage("切换播放音乐: " + nextMusicFile);
    }
}

void MainWindow::updateMusicUIWithTitle(const QString &title)
{
    // 更新UI显示音乐播放状态（带歌曲标题）
    if (m_isMusicPlaying) {
        // 音乐正在播放时的UI状态
        ui->pushButton_stop_music->setVisible(true);  // 显示停止音乐按钮
        
        QString displayTitle = title;
        if (title.contains("sunday")) {
            displayTitle = "《晴天》- 周杰伦";
        } else if (title.contains("tts_")) {
            displayTitle = "《测试音乐》";
        } else {
            displayTitle = "《" + title + "》";
        }
        
        ui->label_conversation_status->setText("🎵 正在播放 " + displayTitle);
        ui->label_conversation_status->setStyleSheet("QLabel { "
            "background: rgba(253, 121, 168, 0.2); "
            "border: 6px solid #fd79a8; "
            "border-radius: 60px; "
            "padding: 24px 48px; "
            "font-size: 30px; "
            "font-weight: bold; "
            "color: #e84393; "
            "margin: 24px 0px; "
        "}");
        logMessage("🎵 音乐播放中: " + displayTitle);
    } else {
        // 音乐停止时的UI状态
        ui->pushButton_stop_music->setVisible(false);  // 隐藏停止音乐按钮
        ui->label_conversation_status->setText("💤 待机中 - 准备开始对话");
        ui->label_conversation_status->setStyleSheet("QLabel { "
            "background: rgba(116, 185, 255, 0.1); "
            "border: 6px solid #74b9ff; "
            "border-radius: 60px; "
            "padding: 24px 48px; "
            "font-size: 30px; "
            "font-weight: bold; "
            "color: #0984e3; "
            "margin: 24px 0px; "
        "}");
        logMessage("🎵 音乐已停止");
    }
}

// 🎵 ================== 音乐对话控制函数实现 ==================

void MainWindow::pauseMusicForConversation()
{
    if (!m_musicPlayer || !m_isMusicPlaying) {
        return; // 没有音乐在播放
    }
    
    // 暂停音乐
    m_musicPlayer->pause();
    m_musicPausedForConversation = true;
    
    // 更新UI状态
    ui->label_conversation_status->setText("🎵 音乐已暂停 - 正在对话");
    ui->label_conversation_status->setStyleSheet("QLabel { "
        "background: rgba(255, 193, 7, 0.2); "
        "border: 6px solid #ffc107; "
        "border-radius: 60px; "
        "padding: 24px 48px; "
        "font-size: 30px; "
        "font-weight: bold; "
        "color: #ff8f00; "
        "margin: 24px 0px; "
    "}");
    
    logMessage("🎵 音乐因对话而暂停");
}

void MainWindow::resumeMusicAfterConversation()
{
    if (!m_musicPlayer || !m_musicPausedForConversation) {
        return; // 音乐没有因对话而暂停
    }
    
    // 恢复音乐播放
    m_musicPlayer->play();
    m_musicPausedForConversation = false;
    m_isMusicPlaying = true;
    
    // 更新UI状态
    updateMusicUI();
    
    logMessage("🎵 对话结束，恢复音乐播放");
}

void MainWindow::adjustMusicVolume(bool increase)
{
    if (!m_musicPlayer) {
        return;
    }
    
    // 调整音量，每次增减10%
    int volumeChange = increase ? 10 : -10;
    m_musicVolume = qBound(0, m_musicVolume + volumeChange, 100);
    
    // 设置新音量
    m_musicPlayer->setVolume(m_musicVolume);
    
    // 记录日志
    QString action = increase ? "增大" : "减小";
    logMessage(QString("🔊 %1音量至 %2%").arg(action).arg(m_musicVolume));
    
    // 可以在这里添加音量显示的UI更新
    // 例如在状态栏显示当前音量
}

// 🏠 ================== 离家回家智能助手函数实现 ==================

void MainWindow::handleLeavingHomeCommand(const QString &text)
{
    // 使用ChatDB获取基础回复
    ChatDB::ChatResponse response = ChatDB::getResponse(text);
    
    QString basicResponse;
    ChatDB::EmotionType emotion = ChatDB::HAPPY;
    
    if (response.isValid() && response.category == ChatDB::HOME) {
        basicResponse = response.text;
        emotion = response.emotion;
    } else {
        // 默认离家回复
        basicResponse = "好的，我来为您播报今天的天气和出行提醒。";
        emotion = ChatDB::NEUTRAL;
    }
    
    // 获取天气信息并生成综合回复
    QString weatherInfo = "";
    if (m_weatherManager) {
        auto weather = m_weatherManager->getCurrentWeatherData();
        if (weather.isValid) {
            // 根据天气情况生成出行建议
            QString weatherAdvice = generateWeatherAdvice(weather);
            weatherInfo = QString("今天%1%2，温度%3。%4")
                         .arg(m_weatherManager->getCurrentCity())
                         .arg(weather.weather)
                         .arg(weather.temperature)
                         .arg(weatherAdvice);
        } else {
            weatherInfo = "天气信息暂时无法获取，请注意查看手机天气预报。";
        }
    } else {
        weatherInfo = "建议您出门前查看天气预报。";
    }
    
    // 生成时间相关的建议
    QString timeAdvice = generateTimeBasedAdvice();
    
    // 综合回复
    QString fullResponse = QString("%1 %2 %3")
                          .arg(basicResponse)
                          .arg(weatherInfo)
                          .arg(timeAdvice);
    
    // 语音回复
    speakResponse(fullResponse);
    sendEmotionCommand(emotion);
    
    logMessage("🏠 离家助手：" + fullResponse);
}

void MainWindow::handleComingHomeCommand(const QString &text)
{
    // 使用ChatDB获取基础回复
    ChatDB::ChatResponse response = ChatDB::getResponse(text);
    
    QString basicResponse;
    ChatDB::EmotionType emotion = ChatDB::HAPPY;
    
    if (response.isValid() && response.category == ChatDB::HOME) {
        basicResponse = response.text;
        emotion = response.emotion;
    } else {
        // 默认回家回复
        basicResponse = "欢迎回家！您辛苦了！";
        emotion = ChatDB::HAPPY;
    }
    
    // 生成家庭状态报告
    QString homeReport = generateHomeStatusReport();
    
    // 生成明天的建议
    QString tomorrowAdvice = generateTomorrowAdvice();
    
    // 综合回复
    QString fullResponse = QString("%1 %2 %3")
                          .arg(basicResponse)
                          .arg(homeReport)
                          .arg(tomorrowAdvice);
    
    // 语音回复
    speakResponse(fullResponse);
    sendEmotionCommand(emotion);
    
    logMessage("🏠 回家助手：" + fullResponse);
}

// 🌤️ 根据天气生成出行建议
QString MainWindow::generateWeatherAdvice(const WeatherManager::WeatherData &weather)
{
    if (weather.weather.contains("雨")) {
        return "记得带伞，注意路面湿滑。";
    } else if (weather.weather.contains("雪")) {
        return "路面可能结冰，请小心慢行，注意保暖。";
    } else if (weather.weather.contains("晴")) {
        if (weather.temperature.contains("℃")) {
            QString tempStr = weather.temperature;
            tempStr.remove("℃");
            bool ok;
            int temp = tempStr.toInt(&ok);
            if (ok && temp > 30) {
                return "天气较热，记得防晒和多喝水。";
            } else if (ok && temp < 5) {
                return "天气较冷，记得多穿衣服保暖。";
            } else {
                return "天气不错，适合外出。";
            }
        } else {
            return "天气晴朗，适合外出。";
        }
    } else if (weather.weather.contains("多云")) {
        return "天气比较舒适，出行愉快。";
    } else if (weather.weather.contains("雾") || weather.weather.contains("霾")) {
        return "能见度较低，开车请注意安全，建议戴口罩。";
    } else if (weather.weather.contains("风")) {
        return "风力较大，注意行车安全。";
    } else {
        return "请注意天气变化，安全出行。";
    }
}

// 🕐 生成基于时间的建议
QString MainWindow::generateTimeBasedAdvice()
{
    QTime currentTime = QTime::currentTime();
    int hour = currentTime.hour();
    
    if (hour >= 6 && hour < 9) {
        return "早上出行，注意交通高峰期，建议提前出发。";
    } else if (hour >= 9 && hour < 11) {
        return "上午时光，道路相对通畅，出行愉快。";
    } else if (hour >= 11 && hour < 14) {
        return "中午时段，阳光可能较强，注意防晒。";
    } else if (hour >= 14 && hour < 17) {
        return "下午时光，适合外出办事。";
    } else if (hour >= 17 && hour < 19) {
        return "傍晚时分，注意交通高峰期，请耐心驾驶。";
    } else if (hour >= 19 && hour < 22) {
        return "晚上出行，注意安全，记得开车灯。";
    } else {
        return "夜深了，出行请特别注意安全。";
    }
}

// 🏠 生成家庭状态报告
QString MainWindow::generateHomeStatusReport()
{
    QStringList statusItems;
    
    // 系统状态
    statusItems.append("系统运行正常");
    
    // 设备状态 - 现在管理3个设备：2个网络显示屏和1个音频设备
    if (m_deviceManager) {
        statusItems.append("网络显示设备已连接");
        statusItems.append("音频设备工作正常");
    }
    
    // 情感控制状态
    if (m_emotionController) {
        statusItems.append("情感显示系统正常");
    }
    
    // 音乐状态
    if (m_isMusicPlaying) {
        statusItems.append("音乐正在播放中");
    }
    
    // 天气监测状态（通过API获取）
    if (m_weatherManager) {
        auto weather = m_weatherManager->getCurrentWeatherData();
        if (weather.isValid) {
            statusItems.append(QString("当前室外%1，%2").arg(weather.weather).arg(weather.temperature));
        } else {
            statusItems.append("天气API连接正常");
        }
    }
    
    QString report = "家庭状态：" + statusItems.join("，") + "。";
    return report;
}

// 📅 生成明天的建议
QString MainWindow::generateTomorrowAdvice()
{
    QDate tomorrow = QDate::currentDate().addDays(1);
    QString dayOfWeek = QLocale::system().dayName(tomorrow.dayOfWeek());
    
    QString advice;
    if (tomorrow.dayOfWeek() == Qt::Monday) {
        advice = "明天是星期一，新的一周开始了，记得调整作息准备工作。";
    } else if (tomorrow.dayOfWeek() == Qt::Friday) {
        advice = "明天是星期五，一周即将结束，加油坚持到最后。";
    } else if (tomorrow.dayOfWeek() == Qt::Saturday || tomorrow.dayOfWeek() == Qt::Sunday) {
        advice = "明天是周末，可以好好休息放松一下。";
    } else {
        advice = QString("明天是%1，继续保持良好的节奏。").arg(dayOfWeek);
    }
    
    // 添加天气预报建议（如果有的话）
    if (m_weatherManager) {
        advice += " 建议明天出门前查看天气预报。";
    }
    
    return advice;
}

// 💡 LED控制处理函数
void MainWindow::handleLedCommand(const QString &text)
{
    if (!m_ledController) {
        speakResponse("抱歉，LED控制系统暂时不可用。");
        return;
    }
    
    QString lowerText = text.toLower();
    
    // 检查LED控制器是否有可用的LED设备
    if (m_ledController->getLedCount() == 0) {
        speakResponse("抱歉，没有检测到可控制的LED设备。");
        return;
    }
    
    // 分析语音指令并执行相应操作
    if (lowerText.contains("开灯") || lowerText.contains("打开灯") || 
        lowerText.contains("开启led") || lowerText.contains("turn on led") ||
        lowerText.contains("led on")) {
        
        if (lowerText.contains("全部") || lowerText.contains("所有") || lowerText.contains("all")) {
            m_ledController->turnOnAllLeds();
            speakResponse("好的，我已经为您打开所有LED灯。");
        } else {
            // 控制第一个LED（通常是主LED）
            if (m_ledController->setLedState(0, true)) {
                QString ledName = m_ledController->getLedName(0);
                speakResponse(QString("好的，我已经为您打开%1。").arg(ledName.isEmpty() ? "LED灯" : ledName));
            } else {
                speakResponse("抱歉，LED灯控制失败，请稍后再试。");
            }
        }
    }
    else if (lowerText.contains("关灯") || lowerText.contains("关闭灯") || 
             lowerText.contains("关闭led") || lowerText.contains("turn off led") ||
             lowerText.contains("led off")) {
        
        if (lowerText.contains("全部") || lowerText.contains("所有") || lowerText.contains("all")) {
            m_ledController->turnOffAllLeds();
            speakResponse("好的，我已经为您关闭所有LED灯。");
        } else {
            // 控制第一个LED
            if (m_ledController->setLedState(0, false)) {
                QString ledName = m_ledController->getLedName(0);
                speakResponse(QString("好的，我已经为您关闭%1。").arg(ledName.isEmpty() ? "LED灯" : ledName));
            } else {
                speakResponse("抱歉，LED灯控制失败，请稍后再试。");
            }
        }
    }
    else if (lowerText.contains("切换灯") || lowerText.contains("反转led") ||
             lowerText.contains("toggle led")) {
        
        if (lowerText.contains("全部") || lowerText.contains("所有") || lowerText.contains("all")) {
            m_ledController->toggleAllLeds();
            speakResponse("好的，我已经为您切换所有LED灯的状态。");
        } else {
            // 切换第一个LED状态
            if (m_ledController->toggleLed(0)) {
                QString ledName = m_ledController->getLedName(0);
                bool isOn = m_ledController->getLedState(0);
                speakResponse(QString("好的，我已经为您%1%2。")
                             .arg(isOn ? "打开" : "关闭")
                             .arg(ledName.isEmpty() ? "LED灯" : ledName));
            } else {
                speakResponse("抱歉，LED灯控制失败，请稍后再试。");
            }
        }
    }
    else {
        // 如果指令不明确，提供帮助信息
        QStringList ledNames = m_ledController->getAllLedNames();
        QString response = QString("我可以帮您控制LED灯。当前检测到%1个LED设备")
                          .arg(m_ledController->getLedCount());
        if (!ledNames.isEmpty()) {
            response += "：" + ledNames.join("、");
        }
        response += "。您可以说\"开灯\"、\"关灯\"或\"切换灯\"来控制它们。";
        speakResponse(response);
    }
    
    // 更新LED状态显示
    updateLedUI();
    
    logMessage("💡 LED控制：" + text);
}

void MainWindow::updateLedUI()
{
    if (!m_ledController) {
        return;
    }
    
    // 这里可以更新UI中LED状态的显示
    // 由于当前UI设计中没有专门的LED状态显示控件，
    // 我们可以在系统日志中记录LED状态
    
    QStringList ledStatuses;
    for (int i = 0; i < m_ledController->getLedCount(); ++i) {
        QString ledName = m_ledController->getLedName(i);
        bool isOn = m_ledController->getLedState(i);
        ledStatuses.append(QString("%1: %2")
                          .arg(ledName.isEmpty() ? QString("LED%1").arg(i+1) : ledName)
                          .arg(isOn ? "开启" : "关闭"));
    }
    
    if (!ledStatuses.isEmpty()) {
        logMessage("💡 LED状态更新：" + ledStatuses.join(", "));
    }
}

// LED控制相关槽函数实现
void MainWindow::onLedStateChanged(int ledIndex, bool isOn)
{
    QString ledName = m_ledController->getLedName(ledIndex);
    logMessage(QString("💡 LED状态变化：%1 %2")
              .arg(ledName.isEmpty() ? QString("LED%1").arg(ledIndex+1) : ledName)
              .arg(isOn ? "已开启" : "已关闭"));
    updateLedUI();
}

void MainWindow::onLedControlResult(bool success, const QString &message)
{
    if (success) {
        logMessage("💡 LED控制成功：" + message);
    } else {
        logMessage("💡 LED控制失败：" + message);
    }
}

void MainWindow::onAllLedsStateChanged(bool allOn)
{
    logMessage(QString("💡 所有LED状态：%1").arg(allOn ? "全部开启" : "全部关闭"));
    updateLedUI();
}

void MainWindow::onToggleLed()
{
    if (m_ledController && m_ledController->getLedCount() > 0) {
        m_ledController->toggleLed(0); // 切换第一个LED
    }
}

void MainWindow::onTurnOnAllLeds()
{
    if (m_ledController) {
        m_ledController->turnOnAllLeds();
    }
}

void MainWindow::onTurnOffAllLeds()
{
    if (m_ledController) {
        m_ledController->turnOffAllLeds();
    }
}

// 🔘 KEY7按键事件处理函数 - 控制LED开关
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    // 检查是否为KEY7按键（在RK3588开发板上对应ESC键）
    if (event->key() == Qt::Key_Escape) {
        if (!m_ledController) {
            logMessage("🔘 KEY7按下，但LED控制器不可用");
            QMainWindow::keyPressEvent(event);
            return;
        }
        
        if (m_ledController->getLedCount() == 0) {
            logMessage("🔘 KEY7按下，但没有检测到LED设备");
            QMainWindow::keyPressEvent(event);
            return;
        }
        
        // 切换第一个LED的状态
        bool currentState = m_ledController->getLedState(0);
        bool newState = !currentState;
        
        if (m_ledController->setLedState(0, newState)) {
            QString ledName = m_ledController->getLedName(0);
            QString statusText = newState ? "开启" : "关闭";
            
            // 语音反馈
            QString response = QString("KEY7按键控制：已%1%2")
                              .arg(statusText)
                              .arg(ledName.isEmpty() ? "LED灯" : ledName);
            speakResponse(response);
            
            // 日志记录
            logMessage(QString("🔘 KEY7按下：%1 %2")
                      .arg(ledName.isEmpty() ? "LED灯" : ledName)
                      .arg(statusText));
            
            // 更新UI显示
            updateLedUI();
        } else {
            logMessage("🔘 KEY7按下，但LED控制失败");
            speakResponse("按键控制LED失败，请稍后再试。");
        }
    }
    
    // 调用父类的按键事件处理
    QMainWindow::keyPressEvent(event);
}

void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    // 检查是否为KEY7按键释放
    if (event->key() == Qt::Key_Escape) {
        // 记录按键释放事件（可选）
        logMessage("🔘 KEY7按键释放");
    }
    
    // 调用父类的按键事件处理
    QMainWindow::keyReleaseEvent(event);
}

// 🎯 LED语音控制辅助函数
void MainWindow::toggleLedByVoice(int ledIndex)
{
    if (!m_ledController || ledIndex >= m_ledController->getLedCount()) {
        speakResponse("指定的LED设备不存在。");
        return;
    }
    
    bool currentState = m_ledController->getLedState(ledIndex);
    bool newState = !currentState;
    
    if (m_ledController->setLedState(ledIndex, newState)) {
        QString ledName = m_ledController->getLedName(ledIndex);
        QString statusText = newState ? "打开" : "关闭";
        speakResponse(QString("好的，我已经为您%1%2。")
                     .arg(statusText)
                     .arg(ledName.isEmpty() ? "LED灯" : ledName));
        updateLedUI();
    } else {
        speakResponse("LED控制失败，请稍后再试。");
    }
}

void MainWindow::turnOnAllLedsByVoice()
{
    if (!m_ledController) {
        speakResponse("LED控制系统不可用。");
        return;
    }
    
    if (m_ledController->turnOnAllLeds()) {
        speakResponse(QString("好的，我已经为您打开所有%1个LED灯。")
                     .arg(m_ledController->getLedCount()));
        updateLedUI();
    } else {
        speakResponse("批量LED控制失败，请稍后再试。");
    }
}

void MainWindow::turnOffAllLedsByVoice()
{
    if (!m_ledController) {
        speakResponse("LED控制系统不可用。");
        return;
    }
    
    if (m_ledController->turnOffAllLeds()) {
        speakResponse(QString("好的，我已经为您关闭所有%1个LED灯。")
                     .arg(m_ledController->getLedCount()));
        updateLedUI();
    } else {
        speakResponse("批量LED控制失败，请稍后再试。");
    }
}

void MainWindow::queryLedStatus()
{
    if (!m_ledController) {
        speakResponse("LED控制系统不可用。");
        return;
    }
    
    int totalLeds = m_ledController->getLedCount();
    if (totalLeds == 0) {
        speakResponse("没有检测到LED设备。");
        return;
    }
    
    int onCount = 0;
    int offCount = 0;
    
    for (int i = 0; i < totalLeds; ++i) {
        if (m_ledController->getLedState(i)) {
            onCount++;
        } else {
            offCount++;
        }
    }
    
    QString statusReport = QString("当前LED状态：共%1个设备，%2个开启，%3个关闭。")
                          .arg(totalLeds)
                          .arg(onCount)
                          .arg(offCount);
    
    speakResponse(statusReport);
    logMessage("🔍 LED状态查询：" + statusReport);
}